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