Pass object between before and after advice?

纵饮孤独 提交于 2019-12-23 01:54:47

问题


Is it possible to create an object in a before advice and pass it to an after advice? For instance, if I have the aspect:

public aspect LoggingAspect {

    pointcut allMethods() : execution(* com.foo.Bar.*(..));

    before() : allMethods() {
        SomeObject foo = makeSomeObject();
    }

    after() : allMethods() {
      // access foo?
    }
}

I can't directly reference foo since it's not in scope (triggers a compiler error). Is there some context available to both advices that I can store foo inside?

Background: I intend to create a unique identifier to refer to this particular invocation of the method and I need access to it in both advices, since I will include it in logging output.

Storing a parameter within my advised class is not an option (since I want it to be unaware of the advice).


回答1:


You could store it in a member variable, but then you have to think about thread safety. Instead I highly recommend to use an around advice.

Object around() : allMethods() {
    SomeObject foo = makeSomeObject();
    Object ret = proceed();
    foo.magic();
    return ret;
}



回答2:


Define it on aspect level exactly as a class member:

public aspect LoggingAspect {
    SomeObject foo;
    before() : allMethods() {
        foo = makeSomeObject();
    }

    after() : allMethods() {
      foo.bar();
    }
}

According to documentation it should work.



来源:https://stackoverflow.com/questions/23339457/pass-object-between-before-and-after-advice

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!