Spring / Spring7 Intermediate to Advanced Interview questions
How does Spring resolve circular dependencies between singleton beans?
For singleton beans wired via setter or field injection, Spring can resolve a circular reference using a three-level cache during bean creation: singletonObjects (fully created beans), earlySingletonObjects (early references already exposed), and singletonFactories (factories that can produce an early reference on demand).
flowchart TD
A[Start creating Bean A] --> B[Instantiate A, expose early reference in singletonFactories]
B --> C[Populate A's properties, needs Bean B]
C --> D[Start creating Bean B]
D --> E[B needs A - fetches A's early reference from cache]
E --> F[B finishes construction using early A]
F --> G[A finishes construction using completed B]
When Bean A's construction needs Bean B, and Bean B needs Bean A back, Spring exposes an early, not-yet-fully-populated reference to A in the third-level cache as soon as A is instantiated (before its own dependencies are injected). When B is created and asks for A, it receives that early reference instead of triggering a second, infinitely-recursive creation of A - B completes using it, and then A's own property population finishes using the now-complete B.
This mechanism only works for setter/field injection, because it depends on being able to hand out a partially-constructed object before its dependencies are filled in. Constructor injection cycles - where A's constructor itself requires B, and B's constructor requires A - cannot be resolved this way, since neither bean can even be instantiated (let alone exposed early) without the other already existing; Spring throws BeanCurrentlyInCreationException in that case.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
