问题
If I have the following code :
@Component
public class A{
@Transactional(propagation = Propagation.REQUIRED)
public void a(){
//logic
b();
//logic
}
@Transactional(propagation = Propagation.REQUIRED)
public void b(){
//logic
}
}
How many transactions open Spring in this code example?
回答1:
It doesn't matter. When calling b()
from a()
it won't be going through the proxy, so any transactional attributes on b()
won't be considered.
The example code has 1 transaction open if a()
or b()
is called through the proxy (i.e. outside of the class) and there isn't a transaction in progress already.
回答2:
I add to @pablo answer the notice that in your example you cannot see the actual difference because your call your method within the same object which make @transaction behavior on the second method transparent with no effect :
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
回答3:
From spring documentation: 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
It only creates one transaction.
回答4:
Refering to the documentation Propagation.REQUIRED
support a current transaction, create a new one if none exists. The answer to your question is :
1 transaction, if there is no transaction when A#a() is called.
0- zero if there is already one because it will be reused.
来源:https://stackoverflow.com/questions/48984379/transactionalpropagation-propagation-required-in-spring