AspectJ “around” and “proceed” with “before / afte

2020-05-29 21:15发布

问题:

Let's say you have three advices: around, before and after.

1) Are before/after called when proceed is called in the around advice, or are they called before/after the around advice as a whole?

2) If my around advice does not call proceed, will the before/after advice be run anyway?

回答1:

With this Test

@Aspect
public class TestAspect {
    private static boolean runAround = true;

    public static void main(String[] args) {
        new TestAspect().hello();
        runAround = false;
        new TestAspect().hello();
    }

    public void hello() {
        System.err.println("in hello");
    }

    @After("execution(void aspects.TestAspect.hello())")
    public void afterHello(JoinPoint joinPoint) {
        System.err.println("after " + joinPoint);
    }

    @Around("execution(void aspects.TestAspect.hello())")
    public void aroundHello(ProceedingJoinPoint joinPoint) throws Throwable {
        System.err.println("in around before " + joinPoint);
        if (runAround) {
            joinPoint.proceed();
        }
        System.err.println("in around after " + joinPoint);
    }

    @Before("execution(void aspects.TestAspect.hello())")
    public void beforeHello(JoinPoint joinPoint) {
        System.err.println("before " + joinPoint);
    }
}

i have following output

  1. in around before execution(void aspects.TestAspect.hello())
  2. before execution(void aspects.TestAspect.hello())
  3. in hello
  4. after execution(void aspects.TestAspect.hello())
  5. in around after execution(void aspects.TestAspect.hello())
  6. in around before execution(void aspects.TestAspect.hello())
  7. in around after execution(void aspects.TestAspect.hello())

so you can see before/after are not called when proceed is called from within @Around annotation.



回答2:

Que: 2) If my around advice does not call proceed, will the before/after advice be run anyway?

Ans: If you don't call proceed in your around advice your before advice as well as your code execution will be skipped but your after advice will execute.But if your after advice use any value from that method everything will be null.So Practically there is no point of using that advice at all...

Hope,I helped.



标签: java aop aspectj