Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the relationships among Spring transactions, async, and circular dependencies

2025-04-11 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces "what are the relationships between Spring transactions, asynchronous and circular dependencies". In daily operation, I believe many people have doubts about the relationship between Spring transactions, asynchronous and circular dependencies. Xiaobian consulted various materials and sorted out simple and easy to use operation methods. I hope to help you answer the doubts about "what are the relationships between Spring transactions, asynchronous and circular dependencies"! Next, please follow the small series to learn together!

preface

There is one kind of circular dependence in circular dependence, which is self-injection: self-dependence.

transaction self-injection

How do you solve the Spring Self-Invocation Transaction Failure? A small partner suggested that he could inject himself to solve the transaction failure.

Specific usage is as follows:

@Slf4j @Service public class OrderBizServiceImpl implements OrderBizService { //Inject yourself @Autowired private OrderBizService orderBizService; @Override public void callBack() throws Exception { //a series of logic //Transaction action required to update order and user amounts orderBizService.updateOrderStatusAndUserBalance(); } @Override @Transactional(rollbackFor = Exception.class) public void updateOrderStatusAndUserBalance() throws Exception { //internal is transaction logic } }

Did you find something amazing, that things worked.

In fact, injecting itself here is actually injecting a proxy object, adjusting the transaction, and also adjusting the transaction of the proxy object, so the transaction takes effect.

Spring Transaction Failure Reason:

Transactions can only be valid if they are applied to public methods; transactions need to be invoked externally, and Spring self-invocation will fail; it is recommended that the transaction annotation @Transactional be generally added to the implementation class.

asynchronous self-injection

It was found that @Transactional annotation can self-inject to solve the problem of transaction failure. In a certain development, it was naturally thought that @Async asynchronous can also self-inject to solve the problem of cyclic dependence.

NO, NO, NO……

The facts tell us that it is impossible!

Start with mistakes:

throw exception part doCreateBean

Start pushing back up exposedObject == bean is that this piece is out of order.

That is to say, asynchronous time, again from the secondary cache and the initial fetch is not the same.

Object earlySingletonReference = getSingleton(beanName, false);

Get Bean from L2 Cache Again

This time, I found that it was different when I got it, so I reported an error.

Then start Debug, according to the logic of circular dependence, when executing to populateBean, attribute assignment, found that there is a dependency on itself, at this time will create itself.

Execute the singleton.getObject method

getEarlyBeanReference

getBeanPostProcessors()

At this time, execute getEarlyBeanReference to determine InfrastructureAdvisorAutoProxyCreator true and call wrapIfNecessary to determine whether to generate a proxy object. No proxy object is generated here.

Then start executing asynchronous AsyncAnnotationBeanPostProcessor that judges false. So no asynchronous generation proxy object logic is performed.

Then keep reading.

It's still normal at this point.

Enter the logic to initializeBean, there is a section called applyBeanPostProcessorsAfterInitialization

Aspect small partner search, so post code keywords. Use IDEA? + Shift + F Search.

applyBeanPostProcessorsAfterInitialization

Loop Execution Postprocessor:

After executing the PostProcessor AsyncAnnotationBeanPostProcessor, the object was changed. This causes the secondary cache to differ from the current Bean.

This is why @Async self-invocation is not allowed, because the object is modified by the proxy later in the initialization phase.

@Transactional Why?

getEarlyBeanReference

getBeanPostProcessors()

First determine InfrastructureAdvisorAutoProxyCreator true to generate a proxy object.

Generating proxy objects

The transaction's processor PersistenceExceptionTranslationPostProcessor is also not executed.

Continue Debug Follow applyBeanPostProcessorsAfterInitialization

The execution ends and the Bean is found unchanged.

summary

@Transactional: Proxy objects have been generated when circular dependencies are promoted from L2 to L3.

@Async: is to generate proxy objects during initialization (initializeBean). @Async then causes the subsequent determination that exposedObject == bean is false, thus throwing an exception.

self-injection

You can see that BeanPostProcessor is executed in two places:

When singletonFactory.getObject is a subclass of SmartInstantiationAwareBeanPostProcessor, getEarlyBeanReference is executed.

All BeanPostProcessor postProcessAfterInitialization methods are executed when initializeBean's applyBeanPostProcessorsAfterInitialization.

There are other places where postprocessors are executed, such as applyBeanPostProcessorsBeforeInitialization, but focus on these two places here.

Proxy objects may be generated in both places.@Transactional is the proxy object generated at getEarlyBeanReference, so it is true when judging whether the Bean has been changed later, while @Async is the proxy object generated asynchronously later, so the judgment does not pass.

At this point, the study of "What are the relationships between Spring transactions, asynchronous and circular dependencies" is over, hoping to solve everyone's doubts. Theory and practice can better match to help you learn, go and try it! If you want to continue learning more relevant knowledge, please continue to pay attention to the website, Xiaobian will continue to strive to bring more practical articles for everyone!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 212

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report