Detailed explanation and understanding of Spring's solution to circular dependencies

Interview answer--》

To put it simply, there is mainly a three-level cache. If a circular dependency is found in it, it will be temporarily placed in the second-level cache (earlySingletonObjects means that there is a circular dependency), and finally placed in the first-level cache (singletonObjects).

Level 1: singletonObjects, Level 2: earlySingletonObjects, Level 3: singletonFactories

Class A (attribute B) .... Class B (attribute A)

Specific process:

1. Object A will be placed in the third-level cache (singletonFactories) at the beginning, and it is found to be dependent on B, and also placed in the third-level cache; ------------------singletonFactories=A,B

2. When starting to inject dependency A in B, move A from level three to level two (delete A in level three); ---------------------- ---singletonFactories=B earlySingletonObjects=A

3. Put B into the first level cache, delete the third level, and complete the injection of B; ---------------------------singletonObjects=B earlySingletonObjects =A

4. Put A into the first-level cache, delete the second-level cache, and complete the injection of A. So far, the injection of A and B is complete. ------------------singletonObjects=A,B

 

Understanding: Why does circular dependency occur if this method is not adopted?

We know that spring instances are singletons by default, and singletonObjects are stored as singleton pools. For example, when instantiating A, it is found that there is a dependency on B, and then a B will be instantiated as an attribute of A, and then B will be put into the singleton pool. Then when B is instantiated, it is found that there is dependency A. If there is no three-level cache at this time, another instance A will be created, and it will be created in a loop. The three-level cache solves this problem.

Guess you like

Origin blog.csdn.net/x18094/article/details/114264694