前置通知:在切入點方法執行之前執行 <aop:before method="" pointcut-ref="" ></aop:before>
后置通知:在切入點方法正常執行之后值。它和異常通知永遠只能執行一個 <aop:after-returning method="" pointcut-ref="" ></aop:before>
異常通知:在切入點方法執行產生異常之后執行。它和后置通知永遠只能執行一個 <aop:after-throwing method="" pointcut-ref="" ></aop:before>
最終通知:無論切入點方法是否正常執行它都會在其后面執行 <aop:after method="" pointcut-ref="" ></aop:before>
配置切入點表達式
id屬性 用於指定表達式的唯一標識。
expression屬性 用於指定表達式內容
此標簽寫在aop:aspect標簽內部只能當前切面使用。
它還可以寫在aop:aspect外面,此時就變成了所有切面可用
環繞通知
配置方式:
<!-- 配置通知bean --> <bean id="txManager" class="com.itheima.utils.TransactionManager"> <property name="dbAssit" ref="dbAssit"></property> </bean>
<aop:config>
<aop:pointcut expression="execution(* com.itheima.service.impl.*.*(..))" id="pt1"/>
<aop:aspect id="txAdvice" ref="txManager">
<!-- 配置環繞通知 -->
<aop:around method="transactionAround" pointcut-ref="pt1"/>
</aop:aspect>
</aop:config>
作用: 用於配置環繞通知
屬性:
method:指定通知中方法的名稱。
pointct:定義切入點表達式
pointcut-ref:指定切入點表達式的引用
說明:
它是spring框架為我們提供的一種可以在代碼中手動控制增強代碼什么時候執行的方式。
注意:
通常情況下,環繞通知都是獨立使用的
Spring框架為我們提供了一個接口:ProceedingJoinPoint。
該接口有一個方法proceed(),此方法就相當於明確調用切入點方法。
該接口可以作為環繞通知的方法參數,在程序執行時,spring框架會為我們提供該接口的實現類供我們使用。
public Object transactionAround(ProceedingJoinPoint pjp) { //定義返回值 Object rtValue = null; try { //獲取方法執行所需的參數 Object[] args = pjp.getArgs(); //前置通知:開啟事務 beginTransaction(); //執行方法 rtValue = pjp.proceed(args); //后置通知:提交事務 commit(); }catch(Throwable e) { //異常通知:回滾事務 rollback(); e.printStackTrace(); }finally { //最終通知:釋放資源 release(); } return rtValue; }