How can the Spring third-level cache resolve circular d…
In Spring, circular dependency refers to the situation where two or more Beans depend on each other, causing initialization issues. Spring provides a three-level cache to resolve circular dependency problems, with the specific solution outlined as follows:
- Expose the partially created object in advance: During the initialization process of a Bean, if a cyclic dependency is detected, Spring will expose the Bean being created to the first-level cache. This way, the first-level cache will have a partially created object.
- Exposing raw objects in advance: Once there is a partially completed object in the first-level cache, Spring will enter the second-level cache. In the second-level cache, if other beans are found to require this partially completed object, Spring will expose the partially completed object to these beans in advance and save references to these beans in the second-level cache.
- Create final object: Once all Beans in the second-level cache that depend on this partially constructed object have been created, Spring will continue to create the final object of the partially constructed object and place it in the third-level cache.
- Injecting dependencies: Once the final object is created, Spring will inject any other beans that depend on this final object into it.
By using this approach, Spring is able to address the issue of circular dependencies. However, it is important to note that the three-level caching mechanism only applies to singleton-scoped Beans, not to prototype-scoped Beans. Therefore, when resolving circular dependency issues, one must pay attention to the scope of the Beans.