文章目录
基于XML的声明式事务控制
由于事务控制基于AOP,所以要导入XML名称空间和约束xmlns:aop
。
还要导入事务的名称空间与约束xmlns:tx
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
https://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
1. 配置事务管理器DataSourceTransactionManager
并注入数据源
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
2. 配置事务的通知<tx:advice>
<tx:advice id="txAdvice" transaction-manager="transactionManager"></tx:advice>
3.配置AOP
通过上面的配置,事务的通知对象已经被指定,现在,只需要将事务的通知对象与切入点联系起来,就构成了切面。
<aop:config>
<!-- 业务逻辑层的所有方法都是事务 -->
<aop:pointcut id="txPointcut" expression="execution(* com.test.service.*.*(..))"/>
<!-- 切入点需要与事务的通知相联系 -->
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"></aop:advisor>
</aop:config>
4. 配置事务属性
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="transfer" isolation="" no-rollback-for="" propagation="" read-only="" rollback-for="" timeout=""/>
</tx:attributes>
</tx:advice>
<tx:method>
属性介绍
- name:方法名(业务逻辑层的一个方法,就是一个事务)可以使用通配符
- isolation:事务的隔离级别(默认值为DEFAULT)
- propagation:用于指定事务的传播行为。默认值是REQUIRED,表示一定会有事务。(增、删、改)的选择
- read-only:用于指定事务是否只读。默认为false。只有查询方法才能设置为true
- timeout:超时时间。默认值-1,表示不会超时。以秒为单位。
- rollback-for:用于指定一个异常,当产生该异常时,事务回滚,产生其他异常时,事务不回滚。默认情况下,任何异常都回滚
- no-rollback-for:用于指定一个异常,表示产生该异常时,事务不回滚,产生其他异常时,事务回滚。默认情况下,任何异常都回滚
事务属性设置示例
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="*" read-only="false" propagation="REQUIRED"></tx:method>
<tx:method name="get*" read-only="true" propagation="SUPPORTS"></tx:method>
</tx:attributes>
</tx:advice>
上面的例子表示,对于以get
开头的方法(查询方法),都是只读的,事务的传播行为是SUPPORTS
,表示可以有事务,也可以没有(取决于具体的实现)
对于除了查询的任意方法(*
通配优先级没有get*
高),都不是只读的,并且一定有事务。
完整配置示例
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="*" read-only="false" propagation="REQUIRED"></tx:method>
<tx:method name="get*" read-only="true" propagation="SUPPORTS"></tx:method>
</tx:attributes>
</tx:advice>
<aop:config>
<!-- 业务逻辑层的所有方法都是事务 -->
<aop:pointcut id="txPointcut" expression="execution(* com.test.service.*.*(..))"/>
<!-- 切入点需要与事务的通知相联系 -->
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"></aop:advisor>
</aop:config>