---
title: "spring事务声明的几种传播特性"
author: "kljjack"
date: "2015-10-19T11:15:57Z"
tags: []
categories: ["企业架构"]
slug: "spring"
draft: false
lastmod: "2015-10-19T11:17:48Z"
id: 2249992
url: "https://kljjack.iteye.com/blog/2249992"
---

最近遇到了一个spring事务导致的问题，所以写了几个小程序了解了一下事务的传播特性，下面分别举例子分别看看事务的传播特性。

 

        事务的几种传播特性

##### 1. PROPAGATION\_REQUIRED: 如果存在一个事务，则支持当前事务。如果没有事务则开启

Java代码  [![收藏代码](http://dorishy.iteye.com/images/icon_star.png)]()

01. /\**
02. * TransactionTestService     test1和test2配有事务（PROPAGATION\_REQUIRED） \*/
03. public interface TransactionTestService {
04. //事务属性 PROPAGATION\_REQUIRED
05. public void test1() throws Exception{
06. avInfoTaskTunnel.insertAvInfoTask();
07. test2();
08. }
09. //事务属性 PROPAGATION\_REQUIRED
10. public void test2() throws Exception{
11. avRequestTunnel.insertAvRequest();
12. throw new Exception();
13. }
14. }
15. /\**
16. * main
17. \*/
18. public class TransactionTestMain {
19. public static void main(String\[] args) throws Exception{
20. TransactionTestService transactionTestService = (TransactionTestService)context.getBean("transactionTestService");
21. try {
22. transactionTestService.test1();
23. } catch (Exception e) {
24. }
25. }
26. }

        上述代码中test1()和test2()都配有PROPAGATION\_REQUIRED事务属性，test1()内部调用test2()，这样 test1()和test2()方法将都处于同一事务之中，当在test2()中抛出异常，会导致test1()和test2()方法中的事务都回滚。

       但是，如果test1()方法对调用test2()时捕获异常，结果会是怎样的呢？ test1应该能正常写入没问题，那么test2呢？

Java代码  [![收藏代码](http://dorishy.iteye.com/images/icon_star.png)]()

1. //test1()中捕获test2()抛出的异常
2. public void test1() throws Exception{
3. avInfoTaskTunnel.insertAvInfoTask();
4. try {
5. test2();
6. }catch (Exception e) {
7. }
8. }

       最后的结果test2()也将会正常的写入。其实，上面情况中如果只是test1()配有PROPAGATION\_REQUIRED事务属性，test2()不配置任何事务属性，发生的结果也是一致的。上面的情形相当于:

Java代码  [![收藏代码](http://dorishy.iteye.com/images/icon_star.png)]()

01. public static void main(String\[] args) throws Exception{
02. Connection con = null;
03. try {
04. con=getConnection();
05. con.setAutoCommit(false);
06. transactionTestService.test1(); //test1()和test2()处于同一事务之中
07. con.commit();
08. } catch (Exception e) {
09. con.rollback();
10. } finally {
11. closeCon();
12. }
13. }

         上述test1()和test2()是同一个类的两个方法，那么要是它们处于不同类呢？

Java代码  [![收藏代码](http://dorishy.iteye.com/images/icon_star.png)]()

01. //main函数不变，test1()中调用test2()地方换成调用另一个类中配有PROPAGATION\_REQUIRED事务属性的方法
02. //不对otherService.test2()捕获异常的情形就没必要说了，必定都回滚。
03. public void test1() throws Exception{
04. avInfoTaskTunnel.insertAvInfoTask();
05. try {
06. otherService.test2();  //PROPAGATION\_REQUIRED事务属性
07. } catch (Exception e) {
08. }
09. }
10. //otherService.test2()
11. public void test2() throws Exception{
12. avRequestTunnel.insertAvRequest();
13. throw new Exception();
14. }

         上述同样捕获了异常，但是结果会怎样呢？ 结果有点出乎意料，与之前test1(),test2()处于同一类的情形不同，这个时候，两个方法都将回滚，并且在调用test1()的地方会抛出下面 异常。这是由于子事务在回滚的时候已经将主事务标记成了rollback-only，这样导致主事务在提交的时候就会抛出下面这个异常。 另外：如果otherService.test2()没有配置任何事务属性，那么test2()抛出异常的时候，将导致test1()和test2()都 回滚。

Java代码  [![收藏代码](http://dorishy.iteye.com/images/icon_star.png)]()

1. org.springframework.transaction.UnexpectedRollbackException: Transaction rolled back because it has been marked as rollback-only

        上述情况网上查询到一种解决方式是在transactionManager中将 globalRollbackOnParticipationFailure 设置为false（默认是true）。但是这样又带来另一个问题，子事务也给一并提交了（这个时候子事务产生异常，不想提交），具体的解决方式还没找到， 但是我觉得不应该将这两个配置在同一事务中。

Xml代码  [![收藏代码](http://dorishy.iteye.com/images/icon_star.png)]()

1. &lt;bean id="transactionManager"
2. class="org.springframework.jdbc.datasource.DataSourceTransactionManager"&gt;
3. &lt;property name="dataSource"&gt;
4. &lt;ref local="dataSource" /&gt;
5. &lt;/property&gt;
6. &lt;property name="globalRollbackOnParticipationFailure" value="false" /&gt;
7. &lt;/bean&gt;

 

##### 2. PROPAGATION\_SUPPORTS: 如果存在一个事务，支持当前事务。如果没有事务，则非事务的执行

Java代码  [![收藏代码](http://dorishy.iteye.com/images/icon_star.png)]()

01. //TransactionTestService     test1（）配有事务（PROPAGATION\_SUPPORTS）
02. public void test1() throws Exception{
03. avInfoTaskTunnel.insertAvInfoTask();
04. throw new Exception();
05. }
06. /\**
07. * main
08. \*/
09. public class TransactionTestMain {
10. public static void main(String\[] args) throws Exception{
11. TransactionTestService transactionTestService = (TransactionTestService)context.getBean("transactionTestService");
12. try {
13. transactionTestService.test1();
14. } catch (Exception e) {
15. }
16. }
17. }

         TransactionTestService的test1()配有PROPAGATION\_SUPPORTS事务属性，我们知道这种情形下如果配的是 PROPAGATION\_REQUIRED事务属性，那么test1()将新建事务运行，但是PROPAGATION\_SUPPORTS属性不会新建，这 种情形下，test1()方法将正常提交。那如果是外层事务配有事务呢？如下所示,此种情形test2()将处于事务之中了。

Java代码  [![收藏代码](http://dorishy.iteye.com/images/icon_star.png)]()

01. //PROPAGATION\_REQUIRED事务属性
02. public void test1() throws Exception{
03. avInfoTaskTunnel.insertAvInfoTask();
04. test2();
05. }
06. //PROPAGATION\_SUPPORTS事务属性
07. public void test2() throws Exception{
08. avRequestTunnel.insertAvRequest();
09. throw new Exception();
10. }

 

##### 3. PROPAGATION\_MANDATORY: 如果已经存在一个事务，支持当前事务。如果没有一个活动的事务，则抛出异常。

 

Java代码  [![收藏代码](http://dorishy.iteye.com/images/icon_star.png)]()

01. //情形1：PROPAGATION\_REQUIRED事务属性  情形2：不配任何事务属性
02. public void test1() throws Exception{
03. avInfoTaskTunnel.insertAvInfoTask();
04. otherService.test2();
05. }
06. //otherService的test2()配置PROPAGATION\_MANDATORY事务属性
07. public void test2() throws Exception {
08. avRequestTunnel.insertAvRequest();
09. throw new Exception();
10. }
11. //test1()处于情形2时抛出异常，test2()不能够提交，但是test1()却是可以成功提交的
12. org.springframework.transaction.IllegalTransactionStateException: No existing transaction found for transaction marked with propagation 'mandatory'

         上述情况，当test1()处于情形1时，会是的test1()和test2()都处于事务当中；test1()处于情形2时，就会抛异常，但是这个时 候test2()不能够提交，但是test1()却是可以成功提交的。此外，还有一点，注意上述test2()是处于另一个类中的，如果是处于同一个类， 那么PROPAGATION\_MANDATORY不会因为外层是否有事务而抛异常。

##### 4. PROPAGATION\_REQUIRES\_NEW: 总是开启一个新的事务。如果一个事务已经存在，则将这个存在的事务挂起。

Java代码  [![收藏代码](http://dorishy.iteye.com/images/icon_star.png)]()

01. //情形1：PROPAGATION\_REQUIRED事务属性  情形2：不配任何事务属性
02. public void test1() throws Exception{
03. avInfoTaskTunnel.insertAvInfoTask();
04. otherService.test2();
05. }
06. //otherService的test2()配置PROPAGATION\_REQUIRES\_NEW事务属性
07. public void test2() throws Exception {
08. avRequestTunnel.insertAvRequest();
09. throw new Exception();
10. }

 上述情况，test1()处于情形2时test2()新建事务，这点没有问题。那如果test1()处于情形1呢？也就是说test1()已经有事务了。结果是test2()处于新的事务中，怎么确定是处于新的事务中呢？看下面代码：

Java代码  [![收藏代码](http://dorishy.iteye.com/images/icon_star.png)]()

01. //test1配置PROPAGATION\_REQUIRED事务属性
02. public void test1() throws Exception{
03. avInfoTaskTunnel.insertAvInfoTask();
04. otherService.test2();  //PROPAGATION\_REQUIRES\_NEW事务属性
05. }
06. //otherService.test2()
07. public void test2() throws Exception{
08. avRequestTunnel.insertAvRequest();
09. throw new Exception();
10. }

         如果是在同一事务中，那么情形将同于讲述PROPAGATION\_REQUIRED属性时的情形，test1()和test2()都将回滚，并且抛出异 常事务被打上rollback-only标记的异常。但是这里，结果就是test2()回滚，test1正常提交，所以 otherService.test2()处于新的事务中。注意：上述情况test2()也是另一个类的方法，如果属于同一类，也就是test1()和 test2()处于同一个类，test1()中调用test2(),那么配置的PROPAGATION\_REQUIRES\_NEW将无效(跟 test2()什么事务属性都没配置一样)。但是如果是main函数中直接调用test2()，那么还是会起一个新的事务。

        另外一种证明test1()和test2()处于不同事务的方式是，在test2()不抛出异常，然后再test1()调用了test2()之后，抛出异常，最后结果是()回滚，test2()正常提交。

 

##### 5. PROPAGATION\_NOT\_SUPPORTED: 总是非事务地执行，并挂起任何存在的事务。

Java代码  [![收藏代码](http://dorishy.iteye.com/images/icon_star.png)]()

01. //test1配置PROPAGATION\_REQUIRED事务属性
02. public void test1() throws Exception{
03. avInfoTaskTunnel.insertAvInfoTask();
04. otherService.test2();  //PROPAGATION\_NOT\_SUPPORTED事务属性
05. }
06. //otherService.test2()
07. public void test2() throws Exception{
08. avRequestTunnel.insertAvRequest();
09. throw new Exception();
10. }

         如果otherService.test2() 没有配置事务属性，那么test2()抛出异常时，test1()和test2()都回滚。但是现在test2()配置了 PROPAGATION\_NOT\_SUPPORTED事务属性，那么test2()将以非事务运行，而test1()继续运行在事务中，也就是说，此 时，test1()回滚,test2()正常提交。注意：如果test1()和test2()在同一类中，那么test2()的 PROPAGATION\_NOT\_SUPPORTED失效。

 

##### 6. PROPAGATION\_NEVER: 总是非事务地执行，如果存在一个活动事务，则抛出异常

Java代码  [![收藏代码](http://dorishy.iteye.com/images/icon_star.png)]()

01. //test1配置PROPAGATION\_REQUIRED事务属性
02. public void test1() throws Exception{
03. avInfoTaskTunnel.insertAvInfoTask();
04. otherService.test2();  //PROPAGATION\_NEVER事务属性
05. }
06. //otherService.test2()
07. public void test2() throws Exception{
08. avRequestTunnel.insertAvRequest();
09. throw new Exception();
10. }
11. //test1()配置PROPAGATION\_REQUIRED事务属性, otherService.test2()配置PROPAGATION\_NEVER事务属性，将抛下面异常：
12. org.springframework.transaction.IllegalTransactionStateException: Existing transaction found for transaction marked with propagation 'never'

 当然上述情况，如果是test1()和test2()在同一类中，那么PROPAGATION\_NEVER也将失效。

 

##### 7. PROPAGATION\_NESTED：如果一个活动的事务存在，则运行在一个嵌套的事务中. 如果没有活动事务, 则按TransactionDefinition.PROPAGATION\_REQUIRED 属性执行

        最容易弄混淆的其实是 PROPAGATION\_REQUIRES\_NEW 和 PROPAGATION\_NESTED。PROPAGATION\_REQUIRES\_NEW 启动一个新的, 不依赖于环境的 "内部" 事务. 这个事务将被完全 commited 或 rolled back 而不依赖于外部事务, 它拥有自己的隔离范围, 自己的锁, 等等. 当内部事务开始执行时, 外部事务将被挂起, 内务事务结束时, 外部事务将继续执行。另一方面, PROPAGATION\_NESTED 开始一个 "嵌套的" 事务, 它是已经存在事务的一个真正的子事务. 嵌套事务开始执行时, 它将取得一个 savepoint. 如果这个嵌套事务失败, 我们将回滚到此 savepoint.。嵌套事务是外部事务的一部分, 只有外部事务结束后它才会被提交。由此可见, PROPAGATION\_REQUIRES\_NEW 和 PROPAGATION\_NESTED 的最大区别在于, PROPAGATION\_REQUIRES\_NEW 完全是一个新的事务, 而 PROPAGATION\_NESTED 则是外部事务的子事务, 如果外部事务 commit, 潜套事务也会被 commit, 这个规则同样适用于 roll back.

Java代码  [![收藏代码](http://dorishy.iteye.com/images/icon_star.png)]()

1. //test1配置PROPAGATION\_REQUIRED事务属性
2. public void test1() throws Exception{
3. avInfoTaskTunnel.insertAvInfoTask();
4. otherService.test2();  //PROPAGATION\_NESTED事务属性
5. }
6. //otherService.test2()
7. public void test2() throws Exception{
8. avRequestTunnel.insertAvRequest();
9. }

         上述情况，如果otherService.test2()配置PROPAGATION\_REQUIRES\_NEW事务属性，这样test1()回滚，但 是test2()正常提交，因为这是两个事务。但是如果otherService.test2()配置PROPAGATION\_NESTED事务属性，那 么test1()和test2()都将回滚。