How Spring Solves Bean Circular Dependencies with a Three‑Level Cache
This article explains Spring's bean lifecycle, detailing how the framework resolves circular dependencies using a three‑level cache (singletonObjects, earlySingletonObjects, singletonFactories), and why a two‑level cache is insufficient, especially when AOP proxies are involved.
Bean Lifecycle
Understanding the bean lifecycle in Spring is essential to see how circular dependencies are handled. Spring's BeanFactory defines many interfaces that represent different stages of a bean's creation, such as instantiation, property population, and initialization.
The doCreateBean method in AbstractAutowireCapableBeanFactory starts bean creation by instantiating the object via reflection. At this point, dependencies annotated with @Autowired have not yet been injected.
Next, populateBean fills the bean's properties. If a required dependency has not been created, Spring will create it before continuing. Afterwards, initializeBean invokes lifecycle callbacks, including methods from Aware interfaces and any BeanPostProcessor implementations.
During initialization, Spring calls setBeanName, setBeanClassLoader, and setBeanFactory for beans implementing the corresponding Aware interfaces. It also executes postProcessBeforeInitialization and postProcessAfterInitialization of all BeanPostProcessor beans, iterating over each implementation.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java High-Performance Architecture
Sharing Java development articles and resources, including SSM architecture and the Spring ecosystem (Spring Boot, Spring Cloud, MyBatis, Dubbo, Docker), Zookeeper, Redis, architecture design, microservices, message queues, Git, etc.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
