戴着假发的程序员出品 抖音ID:戴着假发的程序员 欢迎关注
切面发布-最终通知
spring应用手册(第三部分)
最终通知也是在被增强方法完全执行结束之后执行,最终通知和后置通知的区别在于即使程序中途出现异常,中断之前也会先执行最终通知。就类似于finallly代码块。最终通知同样可以传入JoinPoint,作用和前置通知的一致,这里就不赘述了。
看案例:
我们在Aspect中添加最终通知:
/**
* @author 戴着假发的程序员
*
* @description
*/
@Component
@Aspect
public class DkAspect {
@Pointcut("execution(* com.st.dk.demo8.service..*.*(..))")
public void pointcut1(){}
@After("pointcut1()")
public void after(){
System.out.println("--后置通知--");
}
}
在业务方法中抛出异常,不做处理:
/**
* @author 戴着假发的程序员
*
* @description
*/
@Component
public class InfoService {
public String showInfo(String info){
System.out.println("InfoService-showInfo输出信息:"+info);
String str = null;
str.trim();//抛出空指针异常不做处理
return "info方法返回值";
}
}
测试:
我们会发现虽然程序抛出异常中断,但是中断之前先执行了后置通知。