How Spring Resolves Bean Circular Dependencies with a Three‑Level Cache
This article explains Spring's bean lifecycle, the three‑level cache mechanism (singletonObjects, earlySingletonObjects, singletonFactories) used to break circular dependencies, the role of Aware interfaces and BeanPostProcessor, and why a second‑level cache is essential when AOP proxies are involved.
In everyday Spring development, circular dependencies between beans occur frequently, but Spring hides the complexity by automatically resolving them.
The article first reviews the bean lifecycle and the steps Spring takes when creating a bean: instantiation, property population, initialization, and post‑processing. It highlights key interfaces such as BeanNameAware , BeanFactoryAware , and InitializingBean , and shows where they are invoked.
Spring uses three caches— singletonObjects (first‑level), earlySingletonObjects (second‑level), and singletonFactories (third‑level)—to expose partially constructed beans as ObjectFactory instances. This allows a bean that is still being created to be injected into another bean, breaking the circular reference.
The article demonstrates a scenario where AService depends on BService and vice‑versa, showing how the third‑level cache creates a bean “half‑product” that is later moved to the second‑level cache after proxy creation. It explains why the second‑level cache is necessary when AOP creates proxy objects: without it, each call to singletonFactory.getObject() would generate a new proxy, violating the singleton contract.
Finally, the piece summarizes the full bean creation flow, emphasizes the importance of the three‑level cache for both non‑proxied and AOP‑proxied beans, and encourages readers to experiment with AOP scenarios to see the cache behavior in action.
Top Architect
Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.
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.