Spring声明式事务管理


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类似的操作。

Spring中如何配置Hibernate事务

Struts2整合Spring方法及原理

基于 Spring 设计并实现 RESTful Web Services

Spring-3.2.4 + Quartz-2.2.0集成实例

使用 Spring 进行单元测试

运用Spring注解实现Netty服务器端UDP应用程序

Spring 3.x 企业应用开发实战 PDF完整高清扫描版+源代码

Spring 的详细介绍:请点这里
Spring 的下载地址:请点这里

本文永久更新链接地址

相关内容