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.
More Related questions...