A misunderstanding of Spring transactions
Spring bean assumes the following classes:
Public class Service implement IService {
@ Transactional (readOnly = false, propagation = Propagation. REQUIRED)
Public void methodA (){
.....
MethodB ()
......
}
@ Transactional (readOnly = false, propagation = Propagation. REQUIRES_NEW)
Public void methodB {
......
}
}
Public class ServiceFacade {
@ Autowired
Private Iservice service;
Public void method (){
Service. methodA (){
}
}
}
If you call the ServiceFacade method () method, what is the transaction between methodA and methodB?
In the same transaction or two transactions, does the methodA transaction take effect or does the methodB transaction take effect?
The answer is that the methodA transaction takes effect, and methodB is embedded into methodA to become a transaction.
Why? Does methodB declare Propagation. REQUIRES_NEW?
The answer is from the implementation of Spring transactions. spring transactions are implemented through dynamic AOP proxies.
Generate a proxy for bean. Because methodB is called inside the Service, the execution is not the methodB of the proxy bean, so the transaction statement above methodB is invalid.
When Facade calls the service's methodA method, it actually executes serviceProxy. methodA, so the method is taken over by the spring transaction. The transaction statement takes effect.
The solution is to put methodB in another bean and be called by methodA or facade to call service. methodA () and then call service. methodB.
Summary: Spring transactions are implemented based on dynamic AOP proxies. By default, the preceding transaction statement is invalid when different methods are called in the same class.
The above language expression may not be accurate enough, but it probably means this. If you have a better expression, please let me know. Thank you.