How Spring Solves Circular Dependencies and the Underlying Essence

This article explains Spring's approach to resolving circular dependencies in singleton beans using a three‑level cache, contrasts it with prototype bean limitations, provides a simplified implementation example, and draws an analogy to the classic two‑sum algorithm to illustrate the core concept.

Top Architect
Top Architect
Top Architect
How Spring Solves Circular Dependencies and the Underlying Essence

Spring's handling of circular dependencies has become a popular Java interview question, and this article walks through how the framework resolves such issues for singleton beans.

When two or more singleton beans reference each other, Spring detects the circular reference and, instead of throwing an error, uses internal caches to break the cycle; the article includes diagrams illustrating typical bean reference graphs.

Prototype‑scoped beans do not support circular dependencies; the framework checks for this condition in AbstractBeanFactory and throws a BeanCurrentlyInCreationException when a prototype bean is in creation:

if (isPrototypeCurrentlyInCreation(beanName)) {
    throw new BeanCurrentlyInCreationException(beanName);
}

The core of Spring's solution lies in three maps maintained by DefaultSingletonBeanRegistry: singletonObjects (the fully created singleton pool), singletonFactories (factories for early bean references), and earlySingletonObjects (early, partially constructed bean instances). These act as temporary placeholders during bean creation.

During bean instantiation, Spring first creates the bean instance, stores it in singletonObjects, then populates its fields. If a dependency is not yet fully created, Spring retrieves the early reference from earlySingletonObjects or creates it via singletonFactories, allowing the circular reference to be satisfied without recursion. A GIF in the original article visualizes this three‑level cache workflow.

The article then abstracts the essence of circular dependency resolution, comparing it to the classic two‑sum problem: both involve looking up a needed element in a map and, if absent, storing the current element for future matches. A simple Java implementation of a two‑sum solution is provided:

class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            int complement = target - nums[i];
            if (map.containsKey(complement)) {
                return new int[]{map.get(complement), i};
            }
            map.put(nums[i], i);
        }
        throw new IllegalArgumentException("No two sum solution");
    }
}

Similarly, the article presents a minimal Spring‑like container that stores created beans in a cache map and resolves dependencies by checking the cache before instantiating new beans, effectively demonstrating the same principle.

In conclusion, understanding Spring's three‑level cache mechanism and the underlying map‑lookup pattern helps demystify circular dependency handling and provides a practical foundation for both interview preparation and deeper framework exploration.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendDesign PatternsJavaspringdependency-injectioncircular-dependencySingleton
Top Architect
Written by

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.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.