1. 五种通知
- 前置通知:@Before
- 后置通知:@AfterReturn
- 异常通知:@AfterThrow
- 最终通知:@After
- 环绕通知:@Around
2. 环绕通知的写法
@Pointcut("execution(* com.*.*(..))")
public void pt1(){}
@Around("pt1()")
public Object aroundAdvice(ProceedingJoinPoint pjp){
Object rtValue = null;
try{
System.out.println("前置通知");
rtValue = pjp.proceed(args);//明确调用业务层方法(切入点方法)
System.out.println("后置通知");
return rtValue;
}catch (Throwable t){
System.out.println("异常通知");
throw new RuntimeException(t);
}finally {
System.out.println("最终通知");
}
}
3. 如何配置一个通知类
- 类上加@Aspect注解,标识为通知类
- 类上添加@Component注解,将该类交由spring容器管理
- 在类里面写通知方法
4. 注意事项
- Spring4中的后置通知与最终通知的打印位置不正确。Spring5中改正过来了。