AOP的执行顺序
AOP的配置类
@Aspect
public class LogAspects {
//抽取公共的切入点表达式
//1、本类引用
//2、其他的切面引用
@Pointcut("execution(public int com.wb.study.interview.spring.aop.MathCalculator.*(..))")
public void pointCut(){};
//@Before在目标方法之前切入;切入点表达式(指定在哪个方法切入)
@Before("pointCut()")
public void logStart(JoinPoint joinPoint){
Object[] args = joinPoint.getArgs();
System.out.println(""+joinPoint.getSignature().getName()+"运行。。。@Before:参数列表是:{"+Arrays.asList(args)+"}");
}
@After("com.wb.study.interview.spring.aop.LogAspects.pointCut()")
public void logEnd(JoinPoint joinPoint){
System.out.println(""+joinPoint.getSignature().getName()+"结束。。。@After");
}
//JoinPoint一定要出现在参数表的第一位
@AfterReturning(value="pointCut()",returning="result")
public void logReturn(JoinPoint joinPoint,Object result){
System.out.println(""+joinPoint.getSignature().getName()+"正常返回。。。@AfterReturning:运行结果:{"+result+"}");
}
@AfterThrowing(value="pointCut()",throwing="exception")
public void logException(JoinPoint joinPoint,Exception exception){
System.out.println(""+joinPoint.getSignature().getName()+"异常。。。异常信息:{"+exception+"}");
}
@Around(value="pointCut()")
public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
System.out.println("环绕通知前AAA");
Object proceed = proceedingJoinPoint.proceed();
System.out.println("环绕通知前BBB");
return proceed;
}
}
类:
public class MathCalculator {
public int div(int i,int j){
System.out.println("MathCalculator...div...");
return i/j;
}
}
执行类:
public static void test01(){
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfigOfAOP.class);
MathCalculator mathCalculator = applicationContext.getBean(MathCalculator.class);
System.out.println("spring的版本:"+SpringVersion.getVersion() + "springboot的版本:" + SpringBootVersion.getVersion());
mathCalculator.div(1, 2);
applicationContext.close();
}
版本 | 异常执行结果 | 正常执行结果 |
---|---|---|
spring4(springboot2.0版本以下) springboot2.0以下可能也存在spring5的 | spring的版本:4.3.12.RELEASEspringboot的版本:1.5.9.RELEASE 环绕通知前AAA div运行。。。@Before:参数列表是:{[1, 0]} MathCalculator...div... div结束。。。@After div异常。。。异常信息:{java.lang.ArithmeticException: / by zero} | spring的版本:4.3.12.RELEASEspringboot的版本:1.5.9.RELEASE 环绕通知前AAA div运行。。。@Before:参数列表是:{[1, 1]} MathCalculator...div... 环绕通知前BBB div结束。。。@After div正常返回。。。@AfterReturning:运行结果:{1} |
spring5(springboot2.0版本以上)
| spring的版本:5.2.8.RELEASEspringboot的版本:2.1.9.RELEASE 环绕通知前AAA div运行。。。@Before:参数列表是:{[1, 0]} MathCalculator...div... div异常。。。异常信息:{java.lang.ArithmeticException: / by zero} div结束。。。@After | spring的版本:5.2.8.RELEASEspringboot的版本:2.1.9.RELEASE 环绕通知前AAA div运行。。。@Before:参数列表是:{[1, 2]} MathCalculator...div... div正常返回。。。@AfterReturning:运行结果:{0} div结束。。。@After 环绕通知前BBB |
对比结论 | spring4:环绕通知---》before-》目标方法---》---》after---》AfterThrowing spring5:环绕通知---》before-》目标方法---》---》AfterThrowing ---》after | spring4:环绕通知---》before-》目标方法---》---》环绕通知---》after---》afterReturning spring5:环绕通知---》before-》目标方法---》---》环绕通知---》afterReturning ---》after |