spring學習筆記(23)基於tx/aop配置切面增強事務
阿新 • • 發佈:2019-02-06
在上一篇文章中,我們使用了宣告式事務來配置事務,使事務配置從service邏輯處理中解耦出來。但它還存在一些缺點:
1. 我們只針對方法名的特定進行攔截,但無法利用方法簽名的其它資訊定位,如修飾符、返回值、方法入參、異常型別等。如果我們需要為同名不同參的同載方法配置不同事務就會出問題了。
2. 事務屬性的配置串雖然能包含較多資訊,但配置較易出錯。
針對這些問題,我們可以基於Schema,引入tx和aop的名稱空間來改進我們的配置:
- 引入名稱空間
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc ="http://www.springframework.org/schema/mvc" xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd" >
- tx\aop核心配置
<!-- 配置事務屬性 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="add*" propagation="REQUIRES_NEW" />
<tx:method name="update*" propagation="REQUIRES_NEW" />
<tx:method name ="delete*" propagation="REQUIRES_NEW" />
<tx:method name="*" read-only="true"/>
</tx:attributes>
</tx:advice>
<!-- 配置事務切入點,以及把事務切入點和事務屬性關聯起來 -->
<aop:config proxy-target-class="true">
<aop:pointcut expression="execution(* com.yc.service.*.*(..))"
id="ServicePointcut" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="ServicePointcut" />
</aop:config>
這裡需要特別注意的是,我們需要在標籤中將proxy-target-class配置成true,否則會出現和上一篇文章相同的錯誤:我們定義的類無法轉換成代理類
這裡我們通過來配置我們的事務增強屬性。在標籤中,常見屬性及其說明如下,其中,除了name屬性是必選外,其他都是可選的:
屬性 | 說明 | 預設 | 允許值 |
---|---|---|---|
name | 匹配方法名 | 必須宣告,至少為* | 可使用*萬用字元 |
propagation | 事務傳播行為 | REQUIRED | REQUIRED,SUPPORTS和MANDATORY和REQUIRES_NEW和NOT_SUPPORTED和NEVER和NESTED |
read-only | 設定當前事務是否只讀 | false | true,false |
isolation | 事務隔離級別 | DEFAULT | READ_UNCOMMITTED和READ_COMMITTED和REPEATABLE_READ和SERIALIZABLE |
timeout | 設定事務的超時時間 | -1 | 預設由頂層事務系統決定 |
rollback-for | 內容為異常名,表示當丟擲這些異常時事務回滾,可以用逗號分隔配置多個 | 無預設值 | 可以使用異常名稱的片段進行匹配如ception等 |
no-rollback-for | 內容為異常名,表示當丟擲這些異常時繼續提交事務,可以用逗號分隔配置多個 | 無預設值 | 可以使用異常名稱的片段進行匹配如ception等。 |
在這裡執行和上一篇文章同樣的測試程式,我們會得到相同的結果