Spring基於XML方式配置事務
阿新 • • 發佈:2019-01-26
配置步驟
###一、配置事務管理器###
- 在Bean配置檔案中配置事務管理器。
- 需要注入資料來源。
- 舉個例子:
<!-- 配置事務管理器 -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
###二、 配置事務屬性###
- 需要先匯入 tx 名稱空間。
- 使用
<tx:advice>
元素宣告事務通知,需要指定id屬性,以便AOP把通知和切入點關聯起來。
還需要指定transaction-manager
屬性,其值Bean配置檔案中事務管理器的id屬性值。 - 在
<tx:advice>
元素下宣告<tx:attributes>
元素,用於指定事務屬性。 - 在
<tx:attributes>
元素下可以使用多個<tx:method>
元素指定多種事務屬性。 - 舉個例子:
<!-- 配置事務通知 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <!-- 根據方法名指定事務的屬性 --> <tx:method name="BookShopXmlService" propagation="REQUIRED"/> <tx:method name="get*" read-only="true"/> <tx:method name="find*" read-only="true"/> <tx:method name="*"/> </tx:attributes> </tx:advice>
###三、 配置事務切入點,把事務切入點與事務關聯起來###
- 在
<aop:config>
元素下,使用<aop:pointcut>
元素宣告切入點,其expression
屬性指定切入點表示式,還需要指定id屬性。 - 在 在
<aop:config>
元素下,使用<aop:advisor>
元素宣告一個增強器,將事務通知和切入點關聯起來,使用advice-ref
屬性指定事務通知,用pointcut-ref
屬性指定切入點。 - 舉個例子:
<!-- 配置事務切入點,以及把事務切入點和事務屬性關聯起來 --> <aop:config> <aop:pointcut expression="execution(* com.sqp.spring.service.*.*(..))" id="txPointcut"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/> </aop:config>