@Before 前置通知,在目标方法之前执行
@After 后置通知,在目标方法之后执行
@AfterReturning 返回通知,执行方法结束前执行(异常不执行)
@AfterThrowing 异常通知,出现异常时候执行
@Around 环绕通知
Spring4 对应在SpringBoot1.X版本内
Spring5 对应在SpringBoot2.X
AOP的执行顺序不同了,用代码验证
@Service
public class CalcServiceImpl implement CalcService{
@Override
public int div(int x,int y){
int result= x / y;
System.out.println("=========== CalcService被调用了")
return result;
}
}
@Aspect
@Component
public class MyAspect{
@Before("execution(public int com.practice.*(..))")
public void beforeNotify(){
System.out.println("**********@Befor我是前置通知MyAspect");
}
@After("execution(public int com.practice.*(..))")
public void afterNotify(){
System.out.println("********@After我是后置通知");
}
@AfterReturning("execution(public int com.practice.*(..))")
public void afterReturningNotify(){
System.out.println("*******@AfterReturning我是返回后通知");
}
@AfterThrowing("execution(public int com.practice.*(..))")
public void afterThrowingNotify(){
System.out.println("********@AfterThrowing我是异常通知");
}
@Around("execution(public int com.practice.*(..))")
public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable{
Object retValue =null;
System.out.println("我是环绕通知之前AAA");
retValue= proceedingJoinPoint.proceed();
System.out.println("我是环绕通知之后BBBB");
return retValue;
}
}
对于Spring4 和Spring5 AOP的全部执行顺序有哪些不一样
Spring4:@Test用的是junit.Test
@SpringBootTest
@Runwith(SpringRunner.class)
public class TestAop{
@Autowire
private CalcService calcService;
@Test
public void testAop(){
System.out.println("spring 版本:"+SpringVersion.getVersion()+ "\t"+"springboot版本:"+SpringVersionj.getVersion());
System.out.println();
calcService.div(10,2);
}
}
运行后结果
异常的场景
@SpringBootTest
@Runwith(SpringRunner.class)
public class TestAop{
@Autowire
private CalcService calcService;
@Test
public void testAop(){
System.out.println("spring 版本:"+SpringVersion.getVersion()+ "\t"+"springboot版本:"+SpringVersionj.getVersion());
System.out.println();
calcService.div(10,0);
}
}
在Spring4 正好执行顺序,@Before(前置通知)======@After(后置通知)=====@AfterReturning(正常返回)
异常执行顺序,@Before(前置通知)=====@After(后置通知)=====@AfterThrowing(方法异常)
Spring5:jupiter.api.Test,测试类不需要写Runwith
@SpringBootTest
public class TestAop{
@Autowire
private CalcService calcService;
@Test
public void testAop5(){
System.out.println("spring版本:"+SpringVersion.getVersion()+"\t" +"springboot版本:"+SpringBoot.getVersion());
System.out.println();
calcService.div(10,2);
}
}
执行结果如下;
异常场景:
@SpringBootTest
public class TestAop{
@Autowire
private CalcService calcService;
@Test
public void testAop5(){
System.out.println("spring版本:"+SpringVersion.getVersion()+"\t" +"springboot版本:"+SpringBoot.getVersion());
System.out.println();
calcService.div(10,0);
}
}
总结Spring4和Spring5的AOP执行顺序区别: