分享知識-快樂自己:Spring切入點的表達式和通知類型
阿新 • • 發佈:2018-09-11
win 返回值 size 正常 執行 println ble tps www 2.AOP通知類型
1.切入點的表達式
表達式格式:
execution([修飾符] 返回值類型 包名.類名.方法名(參數))
其他的代替:
<!-- 完全指定一個方法 --> <!-- <aop:before method="log" pointcut="execution(public void com.spring.demo1.UserServiceImpl.save())"/> --> <!-- 修飾符可以不寫,不是必要出現的 --> <!-- <aop:before method="log" pointcut="execution(void com.spring.demo1.UserServiceImpl.save())"/> --> <!-- 返回值類型必須寫,可以用【*】代替 --> <!-- <aop:before method="log" pointcut="execution(* com.spring.demo1.UserServiceImpl.save())"/> --> <!-- 包名必須寫,可以用【*】代替 --> <!-- <aop:before method="log" pointcut="execution(* *.spring.demo1.UserServiceImpl.save())"/> --> <!-- 任意包結構,【*..*】 --> <!-- <aop:before method="log" pointcut="execution(* *..*.UserServiceImpl.save())"/> --> <!-- 類必須寫,可以用【*】代替 --> <!-- <aop:before method="log" pointcut="execution(* *..*.*ServiceImpl.save())"/> --> <!-- 方法必須寫,可以用【*】代替 --> <!-- <aop:before method="log" pointcut="execution(* *..*.*ServiceImpl.save*())"/> --> <!-- 參數必須寫,【*】代表一個參數,【..】代表任意參數 -->
<!-- <aop:before method="log" pointcut="execution(* *..*.*ServiceImpl.save*(..))"/> -->
2.AOP通知類型
1. 前置通知:
* 在目標類的方法執行之前執行。
* 配置文件信息:
<aop:after method="before" pointcut-ref="myPointcut3"/>
* 應用:可以對方法的參數來做校驗
2. 最終通知:
* 在目標類的方法執行之後執行,如果程序出現了異常,最終通知也會執行。
* 在配置文件中編寫具體的配置:
<aop:after method="after" pointcut-ref="myPointcut3"/>
* 應用:例如像釋放資源
3. 後置通知:
* 方法正常執行後的通知。
* 在配置文件中編寫具體的配置:
<aop:after-returning method="afterReturning" pointcut-ref="myPointcut2"/>
* 應用:可以修改方法的返回值
4. 異常拋出通知:
* 在拋出異常後通知
* 在配置文件中編寫具體的配置:
<aop:after-throwing method="afterThorwing" pointcut-ref="myPointcut3"/>
* 應用:包裝異常的信息
5. 環繞通知:
* 方法的執行前後執行。
* 在配置文件中編寫具體的配置:
<aop:around method="around" pointcut-ref="myPointcut2"/>
* 要註意:目標的方法默認不執行,需要使用ProceedingJoinPoint對來讓目標對象的方法執行。
public void around(ProceedingJoinPoint joinPoint){
System.out.println("環繞通知1...");
try {
// 手動讓目標對象的方法去執行
joinPoint.proceed();
} catch (Throwable e) {
e.printStackTrace();
}
System.out.println("環繞通知2...");
}
轉載請跟隨-註:(https://www.cnblogs.com/NEWHOM/p/6803307.html)
分享知識-快樂自己:Spring切入點的表達式和通知類型