Alibaba Interview: Tackling Spring’s Circular Dependency “Chain of Questions”
The article breaks down Spring's circular dependency problem, explains its three typical forms, details the three‑level cache mechanism with code snippets, walks through the step‑by‑step resolution process, and lists scenarios where Spring cannot resolve such dependencies.
Question 1: What is circular dependency?
Circular dependency occurs when multiple objects depend on each other forming a closed loop, such as two beans referencing each other, which can cause injection deadlock in Spring.
Question 2: What forms can Spring circular dependencies take?
Spring can encounter three shapes of circular dependency:
Mutual dependency – A depends on B and B depends on A.
Three‑bean cycle – A depends on B, B depends on C, and C depends on A.
Self‑dependency – a bean depends on itself.
Illustrations:
Question 3: What does Spring’s three‑level cache store?
Level 1 – singletonObjects: cache of fully initialized singleton bean instances.
Level 2 – earlySingletonObjects: cache of early‑exposed singleton instances.
Level 3 – singletonFactories: cache of ObjectFactory objects that can create bean instances.
Code snippets:
/** Cache of singleton objects: bean name to bean instance. */
private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);
/** Cache of early singleton objects: bean name to bean instance. */
private final Map<String, Object> earlySingletonObjects = new HashMap<>(16);
/** Cache of singleton factories: bean name to ObjectFactory. */
private final Map<String, ObjectFactory<?>> singletonFactories = new HashMap<>(16);Question 4: How does the three‑level cache resolve circular dependencies?
The resolution proceeds in four steps:
When getBean(A.class) is invoked, Spring cannot find A in level 1, creates the instance, places it in level 3, and exposes it.
During A’s construction, @Autowired triggers getBean(B.class); Spring repeats the process for B, adding B to level 3.
When B requires A, Spring finds A in level 3, creates a proxy if A is AOP‑enhanced, moves A to level 2, and completes B’s injection, then moves B from level 3 to level 1.
Finally Spring finishes A’s injection, moving A from level 2 to level 1.
Summary diagram:
Animated illustration (GIF) is also provided for deeper understanding.
Question 5: When can Spring not resolve circular dependencies?
Four situations are unsolvable:
Prototype‑scoped beans injected via setter.
Beans injected through constructor injection.
Singleton proxy beans injected via setter.
Beans marked with @DependsOn.
Understanding these mechanisms helps interviewees explain Spring’s internals clearly and demonstrates deep knowledge of the framework.
Architect's Journey
E‑commerce, SaaS, AI architect; DDD enthusiast; SKILL enthusiast
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.
