Spring的声明式事务管理,可以说是开发人员的福音,也是架构师们的法宝;通过这个神器我们可以有效的解决事务不一致、连接泄露等问题
下面我们就介绍一下Spring声明式事务的配置:
1、创建事务管理器
<bean id = "transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
2、制定事务管理
<!-- 声明式事务配置 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="add*" propagation="REQUIRED" rollback-for="Throwable, Exception, RuntimeException"/>
<tx:method name="begin*" propagation="REQUIRED" rollback-for="Throwable, Exception, RuntimeException"/>
<tx:method name="end*" propagation="REQUIRED" rollback-for="Throwable, Exception, RuntimeException"/>
<tx:method name="update*" propagation="REQUIRED" rollback-for="Throwable, Exception, RuntimeException"/>
<tx:method name="del*" propagation="REQUIRED" rollback-for="Throwable, Exception, RuntimeException"/>
<tx:method name="do*" propagation="REQUIRED" rollback-for="Throwable, Exception, RuntimeException"/>
<tx:method name="save*" propagation="REQUIRED" rollback-for="Throwable, Exception, RuntimeException"/>
<tx:method name="modify*" propagation="REQUIRED" rollback-for="Throwable, Exception, RuntimeException"/>
<tx:method name="*" read-only="true" propagation="SUPPORTS" />
</tx:attributes>
</tx:advice>
3、创建切面
<aop:config>
<aop:pointcut expression="execution(* com.test..service.*.*(..))" id="pointCut" />
<aop:advisor pointcut-ref="pointCut" advice-ref="txAdvice"/>
</aop:config>
备注:
事务管理机制说明propagation 属性值
REQUIRED -- 支持当前事务,如果当前没有事务,就新建一个事务。这是最常见的选择。
SUPPORTS -- 支持当前事务,如果当前没有事务,就以非事务方式执行。
MANDATORY -- 支持当前事务,如果当前没有事务,就抛出异常。
REQUIRES_NEW -- 新建事务,如果当前存在事务,把当前事务挂起。
NOT_SUPPORTED -- 以非事务方式执行操作,如果当前存在事务,就把当前事务挂起。
NEVER -- 以非事务方式执行,如果当前存在事务,则抛出异常。
NESTED -- 如果当前存在事务,则在嵌套事务内执行。如果当前没有事务,则进行与PROPAGATION_REQUIRED类似的操作。