Spring2.x与Spring1.x的AOP顺序区别
前置代码
package com.corn.turorial.spring.aop;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
/**
* @author : Jim Wu
* @version 1.0
* @function :
* @since : 2021/1/13 11:29
*/
@Aspect
@Component
public class AopPointCut {
@Pointcut("execution(public * com.corn.turorial.spring.aop.AopTestService.*(..))")
private void pointCut() {
}
@Before(value = "pointCut()")
public void before() {
System.out.println("前置通知...");
}
@Around(value = "pointCut()")
public Object around(ProceedingJoinPoint point) throws Throwable {
System.out.println("环绕前通知..");
Object returnData = null;
try {
returnData = point.proceed();
} catch (Throwable throwable) {
System.out.println("方法出现了异常!");
}
System.out.println("环绕后通知..");
return returnData;
}
@After(value = "pointCut()")
public void after() {
System.out.println("后置通知...");
}
@AfterReturning(value = "pointCut()")
public void afterReturning() {
System.out.println("返回通知...");
}
@AfterThrowing(value = "pointCut()")
public void afterThrowing() {
System.out.println("异常通知...");
}
}
package com.corn.turorial.spring.aop;
import org.springframework.stereotype.Component;
/**
* @author : Jim Wu
* @version 1.0
* @function :
* @since : 2021/1/13 11:28
*/
@Component
public class AopTestService {
public void testAop() {
// int a = 1/0;
System.out.println(" invoke com.corn.turorial.spring.aop.AopTestService.testAop !");
}
}
package com.corn.turorial.spring.aop;
import org.springframework.stereotype.Component;
/**
* @author : Jim Wu
* @version 1.0
* @function :
* @since : 2021/1/13 11:28
*/
@Component
public class AopTestService {
public void testAop() {
// int a = 1/0;
System.out.println(" invoke com.corn.turorial.spring.aop.AopTestService.testAop !");
}
}
最新的 Spring2.xAOP的正常顺序
环绕前通知…
前置通知…
invoke com.corn.turorial.spring.aop.AopTestService.testAop !
返回通知…
后置通知…
环绕后通知…
Spring1.xAOP的正常顺序
环绕前通知…
前置通知…
invoke com.corn.turorial.spring.aop.AopTestService.testAop !
环绕后通知…
后置通知…
返回通知…
最新的 Spring2.xAOP的异常顺序
环绕前通知…
前置通知…
异常通知…
后置通知…
方法出现了异常!
环绕后通知…
Spring1.xAOP的异常顺序
环绕前通知…
前置通知…
方法出现了异常!
环绕后通知…
后置通知…
返回通知…
总结
最新Spring2.xAOP
正常顺序
环绕前->before前置通知->方法执行->afterReturning返回通知->after后置通知->环绕后
异常顺序
环绕前->before前置通知->afterThrowing异常通知->after后置通知->tryCatch里的逻辑->环绕后
Spring1.x
正常顺序
环绕前-> before前置通知 -> 方法执行 -> 环绕后 -> after后置通知 -> afterReturning返回通知
异常顺序
环绕前-> before前置通知 -> tryCatch异常逻辑 -> 环绕后 -> 后置通知 -> 返回通知 (如果捕获了异常没有afterThrowing通知!) 如果没有tryCatch才会走到异常通知