Spring基于XML方式配置事务

 

配置步骤

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

  1. 在Bean配置文件中配置事务管理器。

  2. 需要注入数据源。

  3. 举个例子:

<!-- 配置事务管理器 -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>12345

###二、 配置事务属性###

  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>12345678910

###三、 配置事务切入点,把事务切入点与事务关联起来###

  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>