A misunderstanding of Spring transactions

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.