Post

How Spring Resolves Circular Dependencies: Starting from the Three-Level Cache

Starting from how circular dependencies form, this post explains how Spring's three-level cache exposes half-built beans early, why constructor injection and prototype scope cannot be resolved, how the cache relates to AOP proxies, and how to handle circular dependencies in practice, ordered by recommendation.

How Spring Resolves Circular Dependencies: Starting from the Three-Level Cache

Circular dependencies are a common Spring interview topic, and a pitfall that is easy to hit in real projects. This post starts from the “why” and explains how Spring uses a three-level cache to resolve them, which cases it cannot resolve, and how to handle them in practice.

1. What Is a Circular Dependency

A circular dependency is a loop between beans: A depends on B, and B depends on A. The code below is an illustrative sketch of how such a loop forms.

1
2
3
4
5
6
7
8
9
10
11
@Service
public class A {
    @Autowired
    private B b;
}

@Service
public class B {
    @Autowired
    private A a;
}

This code actually runs in Spring, because Spring has a mechanism that handles cycles caused by field injection. The following sections explain how that mechanism works.

2. How Spring Resolves It: The Three-Level Cache

DefaultSingletonBeanRegistry maintains three maps, commonly referred to as the three-level cache:

LevelNameContentsBean state
1singletonObjectsFully initialized beansReady to use
2earlySingletonObjectsEarly references to beans, exposed before initialization (possibly proxies)Half-built, properties not yet populated
3singletonFactoriesObjectFactory instances that produce early referencesNo reference produced yet

Here is the flow for A and B depending on each other:

sequenceDiagram
    participant C as Spring Container
    participant A
    participant B
    C->>A: Instantiate new A()
    C->>C: Put A's ObjectFactory into level-3 cache
    C->>A: Populate properties, finds it needs B
    C->>B: Create B: instantiate new B()
    C->>C: Put B's ObjectFactory into level-3 cache
    C->>B: Populate properties, finds it needs A
    B->>C: Request A from the container
    C->>C: Levels 1 and 2 miss, run A's ObjectFactory from level 3
    C-->>B: Return A's early reference (also moved to level 2)
    B->>B: Initialization complete
    B-->>C: B complete
    C->>A: Inject B, run A's initialization
    C->>C: Put A into level-1 cache

Step by step:

  1. Create A by calling new (instantiation).
  2. Put A’s ObjectFactory into the level-3 cache, meaning “if anyone needs an early reference to A, ask this factory.”
  3. While populating A’s properties, the container finds it needs B, so it starts creating B.
  4. B is instantiated the same way, and its own ObjectFactory goes into the level-3 cache.
  5. While populating B’s properties, the container finds it needs A. A is still being created and is in neither level 1 nor level 2, so the container runs A’s ObjectFactory from level 3, gets A’s early reference, and moves it into level 2.
  6. B receives A’s reference, finishes initialization, and control returns to A’s flow.
  7. A receives the complete B, finishes initialization, and is placed in the level-1 cache.

The following simplified lookup logic (not Spring source code, for understanding only) shows the idea:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// Simplified sketch, not Spring source code
Object getSingleton(String name) {
    Object bean = singletonObjects.get(name);                 // Level 1
    if (bean == null) {
        bean = earlySingletonObjects.get(name);               // Level 2
    }
    if (bean == null) {
        ObjectFactory<?> factory = singletonFactories.get(name); // Level 3
        if (factory != null) {
            bean = factory.getObject();                       // An AOP proxy may be created here
            earlySingletonObjects.put(name, bean);
            singletonFactories.remove(name);
        }
    }
    return bean;
}

3. The Core Idea: Why Early Exposure Resolves the Cycle

Many people assume the point of the three-level cache is to avoid creating a bean twice. But a singleton is only created once anyway. The real key is this:

Spring splits “instantiation” from “property population and initialization” into two steps, and between those two steps it can expose a reference to the half-built object.

In one sentence: once an object has been created with new, Spring can hand out a reference to it first and finish filling in its contents later.

The A that B receives has not had its properties populated yet, but it is a reference to the same object, so once A is completed, B sees the complete A.

What happens without the cache? Suppose A is still being created and B asks for A. The container has no usable reference to give, so it concludes that A is being created and also needs itself to finish. It then throws BeanCurrentlyInCreationException. The three-level cache exists to make this path work.

4. Cases the Cache Cannot Solve

The three-level cache is not a cure-all. The following three cases fail outright:

CaseWhy it failsResult
Constructor injectionnew A(b) needs B first, and B needs A. No half-built A can be created, so there is nothing to expose.Throws BeanCurrentlyInCreationException, usually wrapped in BeanCreationException
Prototype scopeA new object is created on every request and is not stored in the singleton cache.Also throws an exception
Spring Boot 2.6+The default is spring.main.allow-circular-references=falseFails at startup even when the three-level cache could resolve it

An example of constructor injection (illustrative code):

1
2
3
4
5
6
7
8
9
10
11
@Service
public class A {
    private final B b;
    public A(B b) { this.b = b; }   // Creating A requires B
}

@Service
public class B {
    private final A a;
    public B(A a) { this.a = a; }   // Creating B requires A, so neither can be created
}

5. Why Three Levels? Isn’t Two Enough?

Without AOP, the second level alone is enough. You can put the raw object created by new straight into level 2.

AOP is what changes things. Suppose A needs a proxy, for example because it has @Transactional. Then the A that B receives must be the proxy, and the object the container finally stores must be the same proxy. In the normal flow, however, the proxy is usually created in the last phase of initialization, in postProcessAfterInitialization of a BeanPostProcessor.

If every bean were proxied right after instantiation, the cycle would be resolved, but the bean’s normal lifecycle would be disrupted. So Spring does the following:

  • The level-3 cache stores an ObjectFactory, not the object itself.
  • Only when an early reference is actually needed does Spring call getEarlyBeanReference. At that point AbstractAutoProxyCreator creates the proxy and records it in earlyProxyReferences.
  • When there is no cycle, the factory is never called, and the proxy is created at the end of initialization as usual.
  • When initialization finishes, Spring checks earlyProxyReferences. If a proxy was already created, it does not wrap the bean a second time.

This way, proxies are created early only when needed, and B receives the same object that ends up in the container. That is why the third level exists.

6. Practical Solutions (In Order of Recommendation)

Once you understand the mechanism, the more important question is how to handle a circular dependency in practice. The approaches below are ordered by how strongly they are recommended. All code in this section is illustrative, and the actual implementation should be adapted to your project.

OrderApproachCharacteristicsRecommendation
1Refactor and extract shared logicBreaks the cycle at the design levelPreferred
2Decouple with eventsSuits “notification” style interactionsCommonly used
3@LazyQuick fix, but the cycle remainsTemporary
4ObjectProvider<B>Resolves on demand, with finer controlAlternative to @Lazy
5Setter or field injectionStill requires the setting in item 6Not recommended
6spring.main.allow-circular-references=trueDisables the check entirelyLast resort, only as a temporary measure during upgrades

1. Refactor: Extract a Third Service

Suppose OrderService and UserService call each other, and both need pricing logic. Instead of having the two depend on each other, extract the shared part:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
@Service
public class PricingService {
    public BigDecimal calculate(Order order) {
        // Shared pricing logic
        return ...;
    }
}

@Service
public class OrderService {
    private final PricingService pricingService;   // One-way dependency
    public OrderService(PricingService pricingService) {
        this.pricingService = pricingService;
    }
}

@Service
public class UserService {
    private final PricingService pricingService;   // One-way dependency
    public UserService(PricingService pricingService) {
        this.pricingService = pricingService;
    }
}

Once the cycle is broken, the dependency graph becomes a directed acyclic graph, and the problem is gone at its root.

2. Decouple with Events

If A only needs to notify B to do something, rather than call it directly, you can use an event instead:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
@Service
public class OrderService {
    private final ApplicationEventPublisher publisher;

    public OrderService(ApplicationEventPublisher publisher) {
        this.publisher = publisher;
    }

    public void createOrder(Order order) {
        // Business logic...
        publisher.publishEvent(new OrderCreatedEvent(order.getId()));
    }
}

@Component
public class PointListener {
    @EventListener
    public void onOrderCreated(OrderCreatedEvent event) {
        // Accumulate member points
    }
}

OrderService no longer depends on PointListener, so only one dependency direction remains. @EventListener runs synchronously by default. If you do not want to block the main flow, add @Async.

3. Inject a Proxy with @Lazy

1
2
3
4
5
6
7
@Service
public class A {
    private final B b;
    public A(@Lazy B b) {     // Injects a proxy; the real B is resolved when a method is called
        this.b = b;
    }
}

@Lazy also works with constructor injection. Because a proxy is injected instead of the real B, A can be created without B existing yet. Keep in mind, though, that this only postpones the problem. The cycle in the design remains, so treat this as a temporary workaround.

4. Resolve Lazily with ObjectProvider<B>

1
2
3
4
5
6
7
8
9
10
11
12
@Service
public class A {
    private final ObjectProvider<B> bProvider;

    public A(ObjectProvider<B> bProvider) {
        this.bProvider = bProvider;
    }

    public void doSomething() {
        bProvider.getObject().work();   // Fetches B from the container only when it is used
    }
}

Compared with @Lazy, the point at which ObjectProvider fetches the bean is written explicitly in the code, which makes it easier to understand and test.

5. Use Setter or Field Injection

1
2
3
4
5
6
7
8
9
@Service
public class A {
    private B b;

    @Autowired
    public void setB(B b) {
        this.b = b;
    }
}

This style lets the circular dependency work in Spring 5, but since Boot 2.6 you still need the setting from item 6 for the application to start. For that reason it is not recommended as a new solution.

6. Last Resort: Allow Circular References

1
spring.main.allow-circular-references=true

This setting lets a legacy project start after upgrading to Boot 2.6+, but it only hides the problem. Use it as a temporary measure, and plan a refactoring afterward.

7. Interview Follow-Up Questions

Interviewers often ask follow-up questions one layer at a time. You can answer along the following lines:

  1. How does Spring resolve circular dependencies? Answer: With the three-level cache. After a bean is instantiated and before its properties are populated, Spring exposes an early reference to it.
  2. Why doesn’t constructor injection work? Answer: Constructor injection needs all dependencies before new runs. The half-built object does not exist yet, so there is nothing to expose early. This means separating instantiation from initialization cannot help here.
  3. Why three levels instead of two? Answer: The third level stores an ObjectFactory, so an AOP proxy is only created when an early reference is actually requested. This avoids disrupting the normal initialization flow and ensures the injected object is the same one the container ends up holding.
  4. How do you handle this in practice? Answer: Refactor first to break the cycle at the design level, for example by extracting a shared service or switching to events. @Lazy is only suitable as a temporary measure, and you should not add it just to make an exception go away.

8. Summary

Spring can resolve circular dependencies because the three-level cache allows a half-built object to be referenced early. That is a technical workaround, not a good design reason. A circular dependency usually means the responsibilities between beans are not split properly. When you encounter one, first review the design: extract shared logic and turn notifications into events, rather than relying on the framework to tolerate the cycle. Understanding the three-level cache helps you explain the mechanism clearly in interviews and while debugging. What actually prevents the problem is keeping dependencies one-way from the start, at the design stage.

This post is licensed under CC BY 4.0 by the author.