Question

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).

Was it helpful?

Solution

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;
}

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top