@Transactional(传播= Propagation.REQUIRED)在spring?

@Transactional(propagation = Propagation.REQUIRED) in spring?

如果我有以下代码:

@Component
public class A{ 

@Transactional(propagation = Propagation.REQUIRED)
public void a(){
    //logic
    b();
 //logic
}

@Transactional(propagation = Propagation.REQUIRED)
public void b(){
    //logic
} 
}

在此代码示例中打开了多少事务 Spring?

来自 spring 文档:https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/transaction/annotation/Propagation.html

REQUIRED: Support a current transaction, create a new one if none exists

它只创建一个交易。

没关系。当从 a() 调用 b() 时,它不会通过代理,因此不会考虑 b() 上的任何事务属性。

如果通过代理调用 a()b()(即在 class 之外)并且没有正在进行的交易,则示例代码有 1 个交易打开.

参考documentation Propagation.REQUIRED支持当前交易,如果none存在则创建一个新交易。您的问题的答案是:

1个事务,如果调用A#a()时没有事务。

0- 如果已有一个则为零,因为它将被重复使用。

我添加到@pablo answer 注意,在你的例子中你看不到实际的区别,因为你在同一个对象中调用你的方法,这使得第二个方法的@transaction 行为透明而没有效果:

In proxy mode (which is the default), only external method calls coming in through the proxy are intercepted. This means that self-invocation, in effect, a method within the target object calling another method of the target object, will not lead to an actual transaction at runtime even if the invoked method is marked with @Transactional