从同一个 bean 调用时 Transactional.TxType.REQUIRES_NEW 是否开始新事务?

Does Transactional.TxType.REQUIRES_NEW start a new transaction when called from the same bean?

据我所知

In proxy mode (which is the default), only 'external' method calls coming in through the proxy will be intercepted. This means that 'self-invocation', i.e. a method within the target object calling some other method of the target object, won't lead to an actual transaction at runtime even if the invoked method is marked with @Transactional!

但这里是:Transactional.TxType.REQUIRES_NEW

是否会创建第二笔交易?

@Service
public class SomeService {
    
    @Transactional
    public void doSomeLogic() {
        // some logic
        doOtherThings();
        // some logic
    }

    @Transactional(Transactional.TxType.REQUIRES_NEW)
    private void doOtherThings() {
        // some logic
    }

要获得此问题的答案,您需要了解 代理的工作原理

当您在 bean 中注释方法时,代理将使用适当的逻辑包装该 bean。这意味着如果您调用 bean 的注释方法,请求将首先发送到代理对象(以 $ 命名),然后代理对象将调用 bean 的方法。如果此方法调用同一 bean 的另一个方法,它将调用它而不调用具有事务管理逻辑 e.x.

的代理。

示例:这是将由代理包装的代码及其工作的适当图表。

@Service
public class SomeService {

    @Transactional
    public void foo() {
        // this next method invocation is a direct call on the 'this' reference
        bar();
    }
    
    @Transactional(Transactional.TxType.REQUIRES_NEW)
    public void bar() {
        // some logic...
    }
}

Source

因此,答案是

希望现在更清楚了。