1. 程式人生 > >Spring基於XML方式配置事務

Spring基於XML方式配置事務

配置步驟

###一、配置事務管理器###

  1. 在Bean配置檔案中配置事務管理器。
  2. 需要注入資料來源。
  3. 舉個例子:
<!-- 配置事務管理器 -->
<bean id="transactionManager" 
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
	<property name="dataSource" ref="dataSource"></property>
</bean>

###二、 配置事務屬性###

  1. 需要先匯入 tx 名稱空間。
  2. 使用<tx:advice>元素宣告事務通知,需要指定id屬性,以便AOP把通知和切入點關聯起來。
    還需要指定transaction-manager屬性,其值Bean配置檔案中事務管理器的id屬性值。
  3. <tx:advice>元素下宣告<tx:attributes>元素,用於指定事務屬性。
  4. <tx:attributes>元素下可以使用多個<tx:method>元素指定多種事務屬性。
  5. 舉個例子:
<!-- 配置事務通知 -->
<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>

###三、 配置事務切入點,把事務切入點與事務關聯起來###

  1. <aop:config>元素下,使用<aop:pointcut>元素宣告切入點,其expression屬性指定切入點表示式,還需要指定id屬性。
  2. 在 在<aop:config>元素下,使用<aop:advisor>元素宣告一個增強器,將事務通知和切入點關聯起來,使用 advice-ref屬性指定事務通知,用pointcut-ref屬性指定切入點。
  3. 舉個例子:
<!-- 配置事務切入點,以及把事務切入點和事務屬性關聯起來 -->
<aop:config>
	<aop:pointcut expression="execution(* com.sqp.spring.service.*.*(..))"
		id="txPointcut"/>
	<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
</aop:config>