【精选】spring源码走读系列 —— 事务的传播机制 - TransactionDefinition

📅 2026-11-30 👤 拼多多助力营销技巧 📂 拼多多助力网站平台 👁️ 281 次阅读

本文的源码位于 org.springframework.transaction.TransactionDefinition

该类定义了事务的传播机制

PROPAGATION_REQUIRED

spring 的默认传播机制 。支持方法在当前事务中运行,如果当前不存在事务则新建一个事务。所以如果配置为该级别,则一定能保证在事务中运行。

/**

* Support a current transaction; create a new one if none exists.

* Analogous to the EJB transaction attribute of the same name.

*

This is typically the default setting of a transaction definition,

* and typically defines a transaction synchronization scope.

*/

int PROPAGATION_REQUIRED = 0;

PROPAGATION_SUPPORTS

如果运行环境上下文处在事务中,支持该方法在事务中运行。 如果没有事务,则不会主动开启事务。

spring提醒使用这个隔离级别要格外小心,尤其是和PROPAGATION_REQUIRED或 PROPAGATION_REQUIRES_NEW 交织在一起使用时。

(不过工程上隔离级别都会设置为全局的,不会每个方法都定义一个级别,所以一般不会混用吧)

/**

* Support a current transaction; execute non-transactionally if none exists.

* Analogous to the EJB transaction attribute of the same name.

*

NOTE:For transaction managers with transaction synchronization,

* {@code PROPAGATION_SUPPORTS} is slightly different from no transaction

* at all, as it defines a transaction scope that synchronization might apply to.

* As a consequence, the same resources (a JDBC {@code Connection}, a

* Hibernate {@code Session}, etc) will be shared for the entire specified

* scope. Note that the exact behavior depends on the actual synchronization

* configuration of the transaction manager!

*

In general, use {@code PROPAGATION_SUPPORTS} with care! In particular, do

* not rely on {@code PROPAGATION_REQUIRED} or {@code PROPAGATION_REQUIRES_NEW}

*withina {@code PROPAGATION_SUPPORTS} scope (which may lead to

* synchronization conflicts at runtime). If such nesting is unavoidable, make sure

* to configure your transaction manager appropriately (typically switching to

* "synchronization on actual transaction").

* @see org.springframework.transaction.support.AbstractPlatformTransactionManager#setTransactionSynchronization

* @see org.springframework.transaction.support.AbstractPlatformTransactionManager#SYNCHRONIZATION_ON_ACTUAL_TRANSACTION

*/

int PROPAGATION_SUPPORTS = 1;

PROPAGATION_MANDATORY

MANDATORY 强制性的

表示该方法运行的时候必须存在事务,否则报错。

/**

* Support a current transaction; throw an exception if no current transaction

* exists. Analogous to the EJB transaction attribute of the same name.

*

Note that transaction synchronization within a {@code PROPAGATION_MANDATORY}

* scope will always be driven by the surrounding transaction.

*/

int PROPAGATION_MANDATORY = 2;

PROPAGATION_REQUIRES_NEW

创建一个新事务,挂起当前事务(若存在)

/**

* Create a new transaction, suspending the current transaction if one exists.

* Analogous to the EJB transaction attribute of the same name.

*

NOTE:Actual transaction suspension will not work out-of-the-box

* on all transaction managers. This in particular applies to

* {@link org.springframework.transaction.jta.JtaTransactionManager},

* which requires the {@code javax.transaction.TransactionManager} to be

* made available it to it (which is server-specific in standard Java EE).

*

A {@code PROPAGATION_REQUIRES_NEW} scope always defines its own

* transaction synchronizations. Existing synchronizations will be suspended

* and resumed appropriately.

* @see org.springframework.transaction.jta.JtaTransactionManager#setTransactionManager

*/ 拼多多帮助力入口

int PROPAGATION_REQUIRES_NEW = 3;

PROPAGATION_NOT_SUPPORTED

同样会挂起当前事务(若存在),但是该方法不会在事务中运行

可以和PROPAGATION_REQUIRES_NEW做个比较

/**

* Do not support a current transaction; rather always execute non-transactionally.

* Analogous to the EJB transaction attribute of the same name.

*

NOTE:Actual transaction suspension will not work out-of-the-box

* on all transaction managers. This in particular applies to

* {@link org.springframework.transaction.jta.JtaTransactionManager},

* which requires the {@code javax.transaction.TransactionManager} to be

* made available it to it (which is server-specific in standard Java EE).

*

Note that transaction synchronization isnotavailable within a

* {@code PROPAGATION_NOT_SUPPORTED} scope. Existing synchronizations

* will be suspended and resumed appropriately.

* @see org.springframework.transaction.jta.JtaTransactionManager#setTransactionManager

*/

int PROPAGATION_NOT_SUPPORTED = 4;

PROPAGATION_NEVER

该方法运行时若上下文存在事务,则报错

可以同PROPAGATION_MANDATORY比较

/**

* Do not support a current transaction; throw an exception if a current transaction

* exists. Analogous to the EJB transaction attribute of the same name.

*

Note that transaction synchronization isnotavailable within a

* {@code PROPAGATION_NEVER} scope.

*/

PROPAGATION_NESTED

如果运行环境上下文存在事务,则该方法会嵌套在该事务中运行。 如果不存在事务,则会创建一个事务。

嵌套事务只有部分事务管理器才支持。

/**

* Execute within a nested transaction if a current transaction exists,

* behave like {@link #PROPAGATION_REQUIRED} otherwise. There is no

* analogous feature in EJB.

*

NOTE:Actual creation of a nested transaction will only work on

* specific transaction managers. Out of the box, this only applies to the JDBC

* {@link org.springframework.jdbc.datasource.DataSourceTransactionManager}

* when working on a JDBC 3.0 driver. Some JTA providers might support

* nested transactions as well.

* @see org.springframework.jdbc.datasource.DataSourceTransactionManager

*/```

Juergen Hoeller 对两个传播机制的解析 & 提供了一些使用案例

PROPAGATION_REQUIRES_NEW starts a new, independent “inner” transaction for the given scope. This transaction will be committed or rolled back completely independent from the outer transaction, having its own isolation scope, its own set of locks, etc. The outer transaction will get suspended at the beginning of the inner one, and resumed once the inner one has completed. PROPAGATION_REQUIRES_NEW 启动一个新的、独立的“内部”事务。此事务将完全独立于外部事务提交或回滚,具有自己的隔离范围、自己的锁集等。外部事务将在内部事务开始时暂停,并在内部事务完成后恢复。 Such independent inner transactions are for example used for id generation through manual sequences, where the access to the sequence table should happen in its own transactions, to keep the lock there as short as possible. The goal there is to avoid tying the sequence locks to the (potentially much longer running) outer transaction, with the sequence lock not getting released before completion of the outer transaction. 例如,这种独立的内部事务用于通过手动序列生成id,其中对序列表的访问应该发生在其自己的事务中,以使那里的锁尽可能短。这样做的目的是避免将序列锁绑定到(可能会运行更长时间)外部事务,因为在外部事务完成之前,序列锁不会被释放。 PROPAGATION_NESTED on the other hand starts a “nested” transaction, which is a true subtransaction of the existing one. What will happen is that a savepoint will be taken at the start of the nested transaction. íf the nested transaction fails, we will roll back to that savepoint. The nested transaction is part of of the outer transaction, so it will only be committed at the end of of the outer transaction. PROPAGATION_NESTED 将启动“嵌套”事务,这是现有事务的真正子事务。将发生的情况是,将在嵌套事务开始时获取一个保存点。如果嵌套事务失败,我们将回滚到该保存点。嵌套事务是外部事务的一部分,因此它将仅在外部事务结束时提交。 Nested transactions essentially allow to try some execution subpaths as subtransactions: rolling back to the state at the beginning of the failed subpath, continuing with another subpath or with the main execution path there - all within one isolated transaction, and not losing any previous work done within the outer transaction. 嵌套事务本质上允许将一些执行子路径作为子事务进行尝试:回滚到失败子路径开始时的状态,继续使用另一个子路径或主执行路径——所有这些都在一个独立事务中进行,并且不会丢失外部事务中以前完成的任何工作。 For example, consider parsing a very large input file consisting of account transfer blocks: The entire file should essentially be parsed within one transaction, with one single commit at the end. But if a block fails, its transfers need to be rolled back, writing a failure marker somewhere. You could either start over the entire transaction every time a block fails, remembering which blocks to skip - or you mark each block as a nested transaction, only rolling back that specific set of operations, keeping the previous work of the outer transaction. The latter is of course much more efficient, in particular when a block at the end of the file fails. 例如,考虑解析一个由帐户转移块组成的非常大的输入文件:整个文件应该在一个事务中被解析,最后一个提交。但如果一个块失败了,它的传输需要回滚,在某处写一个失败标记。您可以在每次块失败时重新启动整个事务,记住要跳过哪些块,或者将每个块标记为嵌套事务,只回滚特定的操作集,保留外部事务的先前工作。后者当然效率更高,尤其是当文件末尾的块失败时。

所以PROPAGATION_NESTED最重要的还是有一个savepoint的概念。 但实际使用时还是要捕获嵌套事务内发生的异常。

推荐链接

标签: 拼多多助力网站平台 赚钱项目 拼多多助力网 首码项目 手赚APP
拼多多助力营销技巧