生活随笔
收集整理的這篇文章主要介紹了
spring基于注解的AOP配置 中的环绕通知 步骤写法
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
由于,使用注解配置AOP的bug
在使用注解配置AOP時,會出現(xiàn)一個bug. 四個通知的調(diào)用順序依次是:前置通知,最終通知,后置通知. 這會導(dǎo)致一些資源在執(zhí)行最終通知時提前被釋放掉了,而執(zhí)行后置通知時就會出錯.
所以注解的方式改用,注解環(huán)繞通知。能更為精確。
基于這層代碼進(jìn)行修改:https://blog.csdn.net/qq847196660/article/details/96442929
1.修改bean.xml 配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:aop="http://www.springframework.org/schema/aop"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beanshttps://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/aophttps://www.springframework.org/schema/aop/spring-aop.xsdhttp://www.springframework.org/schema/contexthttps://www.springframework.org/schema/context/spring-context.xsd"><!--配置spring 創(chuàng)建容器時要掃描的包-->
<context:component-scan base-package="wuwei" ></context:component-scan><!--配置spring 開啟注解AOP的支持-->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy></beans>
2.重寫通知類:Logger
//記錄日志的工具類(也叫通知類),它里面提供了公共的代碼
@Component("logger") //通知類的注解名稱
@Aspect //表示當(dāng)前類是一個切面類
public class Logger {//通用切入點(diǎn)表達(dá)式方法的注解@Pointcut("execution(* wuwei.service.impl.*.*(..))")private void pt1(){ }
// 環(huán)繞通知允許我們更自由地控制增強(qiáng)代碼執(zhí)行的時機(jī)
//
// Spring框架為我們提供一個接口ProceedingJoinPoint,**可以理解為控制器**
// 它的實(shí)例對象可以作為環(huán)繞通知方法的參數(shù),通過參數(shù)控制被增強(qiáng)方法的執(zhí)行時機(jī).
//
// ProceedingJoinPoint對象的getArgs()方法返回被攔截的參數(shù)
// ProceedingJoinPoint對象的proceed()方法執(zhí)行被攔截的方法// 環(huán)繞通知方法,返回Object類型@Around("pt1()")public Object printLogAround(ProceedingJoinPoint pjp) {Object rtValue = null;try {Object[] args = pjp.getArgs();beforePrintlog(); // 執(zhí)行前置通知rtValue = pjp.proceed(args);// 執(zhí)行被攔截方法afterReturningPrintlog(); // 執(zhí)行后置通知}catch(Throwable e) {afterThrowingPrintlog(); // 執(zhí)行異常通知}finally {afterPrintlog(); // 執(zhí)行最終通知}return rtValue;}//@Before("pt1()")//引用已提取出的通用表達(dá)式,也就是把這個通知指向某包下某實(shí)現(xiàn)類中的某實(shí)現(xiàn)方法public void beforePrintlog(){//用于打印日志:計劃讓其在切入點(diǎn)方法執(zhí)行前執(zhí)行,也就是前置通知//切入點(diǎn)方法就是業(yè)務(wù)層的方法System.out.println("logger類中 前置通知 方法開始記錄日志了。。。");}// @AfterReturning("pt1()")public void afterReturningPrintlog(){//后置通知System.out.println("logger類中 后置通知 方法開始記錄日志了。。。");}// @AfterThrowing("pt1()")public void afterThrowingPrintlog(){//異常通知System.out.println("logger類中 異常通知 方法開始記錄日志了。。。");}// @After("pt1()")public void afterPrintlog(){//最終通知System.out.println("logger類中 最終通知 方法開始記錄日志了。。。");}}
3.其他的代碼參照上面的xml 配置方式寫就行
總結(jié)
以上是生活随笔為你收集整理的spring基于注解的AOP配置 中的环绕通知 步骤写法的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。