自定义切面编程,执行过程分析Around > Before > Around > After > AfterReturning[AfterThrowing]

AspectJ:面向切面的框架。

主要包括:切面包含切点(Pointcut)及通知(Advice),完整的Aop还应包含连接点(Joint point);

响应顺序:通知响应顺序如下:

                  

通过代码分支得知响应顺序为

Around > Before > Around > After > AfterReturning[AfterThrowing]

说明:

 1)上图中三个绿色部分比较特殊这里需要说明一下:

      通知里比较特殊的是环绕通知(Arround),环绕通知贯穿切点方法(业务代码),需要通过

    Object o = ProceedingJoinPoint.proceed();

       完成切点方法(业务代码)并将其执行结果返回,已保证调用链条继续向下执行。

      也就是说, 如果业务代码报错了,ProceedingJoinPoint.proceed()之后的Arround也就不执行了。

2)切点方法(业务代码)执行报错了,并不影响After的执行。

3) 根据切点方法(业务代码)执行过程是否报错,决定执行AfterReturning或者AfterThrowing。

示例代码:

          这里只给出Arround的代码

@Around("demoAspect()")
public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable{
    System.out.println("Around processed before");
    Object o = joinPoint.proceed();
    System.out.println("Around processed end");
    return o;
}

    Arround的使用要求类似Filter,joinPoint.proceed()完成切点方法(业务代码)的继续执行,当发现加入@Arround通知 后无法执行@Before或者业务代码,或者没有返回值时,可以考虑该通知使用有误。

发布了15 篇原创文章 · 获赞 14 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/master336/article/details/104366893