Circular Dependencies in Spring
Circular dependencies in Spring happen when two or more beans need each other, directly or through a chain: OrderService needs InventoryService, and InventoryService needs OrderService. The container cannot finish creating either one first, so in Spring Boot the application refuses to start and prints the cycle. The error is easy to work around and just as easy to work around badly, so it pays to understand why it happens and which fixes improve the design.
This tutorial reproduces a real cycle, explains why constructor injection cannot resolve it and how Spring's early references work for setter injection, and then compares the fixes: redesigning the classes, publishing events, @Lazy, ObjectProvider and the spring.main.allow-circular-references property, from best to last resort.
1. What Is a Circular Dependency?
A circular dependency is a loop in the graph of bean dependencies. The loop can be short (A needs B, B needs A) or long (A needs B, B needs C, C needs A). Long loops are common in growing code bases because no single class looks wrong on its own.
2. Why Circular Dependencies Are a Problem
- Startup fails: since Spring Boot 2.6, circular references are prohibited by default, so the application does not start.
- Unclear responsibilities: two classes that call each other usually share one responsibility or mix two.
- Half-built objects: when a cycle is allowed, one bean receives a reference to another that is not fully initialized yet.
- Hard testing: you cannot create either class in a unit test without the other.
3. Reproducing the Error
An order service reserves stock when an order is placed. Later, someone adds a feature: when stock is replenished, inventory re-checks back-ordered orders. Both classes now call each other:
@Service
public class OrderService {
private final InventoryService inventory;
public OrderService(InventoryService inventory) {
this.inventory = inventory;
}
public void place(String orderId, String sku, int quantity) {
inventory.reserve(sku, quantity);
}
public void retryBackorders(String sku) {
// find back-ordered orders for the sku and place them again
}
}
@Service
public class InventoryService {
private final OrderService orders;
public InventoryService(OrderService orders) {
this.orders = orders;
}
public void reserve(String sku, int quantity) {
// decrease stock
}
public void replenish(String sku, int quantity) {
// increase stock, then:
orders.retryBackorders(sku);
}
}
Spring Boot stops with a failure report that draws the cycle:
***************************
APPLICATION FAILED TO START
***************************
Description:
The dependencies of some of the beans in the application context form a cycle:
┌─────┐
| orderService defined in file [.../OrderService.class]
↑ ↓
| inventoryService defined in file [.../InventoryService.class]
└─────┘
Action:
Relying upon circular references is discouraged and they are prohibited by default. Update your application to remove the dependency cycle between beans. As a last resort, it may be possible to break the cycle automatically by setting spring.main.allow-circular-references to true.
Underneath the report is a BeanCurrentlyInCreationException with the message "Requested bean is currently in creation: Is there an unresolvable circular reference?"
4. Why Spring Cannot Resolve Constructor Cycles
Java can only pass a finished object reference to a constructor. OrderService's instance does not exist until its constructor returns, and that constructor is waiting for InventoryService. Spring keeps a set of beans "currently in creation"; when it is asked for one of them again, it knows it is in a loop and stops.
5. How Early References Resolve Setter Cycles
With setter or field injection, the constructor does not need the other bean, so Spring can do this:
- Call
OrderService's constructor. The object exists but has no dependencies yet. - Register an early reference to it in an internal cache of singletons that are still being built (often called the "three-level cache": finished singletons, early references, and factories that create early references).
- Inject dependencies into
OrderService: createInventoryService, whose setter asks forOrderServiceand receives the early reference. - Finish
InventoryService, then finishOrderService.
It works, but InventoryService briefly holds a reference to an object whose initialization has not completed. That is why Spring Boot 2.6 switched it off by default with spring.main.allow-circular-references=false. Plain Spring Framework applications still allow it unless configured otherwise.
6. How to Fix Circular Dependencies
From the best fix to the last resort:
| Fix | How | Improves design? | Use when |
|---|---|---|---|
| 1. Move the shared logic | Extract the code both classes need into a third bean | Yes | Two classes share a responsibility |
| 2. Reverse one direction with events | One side publishes an event; the other listens | Yes | One call is a notification ("something happened") |
| 3. Pass data instead of the bean | Give the method the values it needs as arguments | Yes | One class only reads data from the other |
4. @Lazy on one injection point | Spring injects a lazy proxy that resolves the real bean on first use | No | A quick, local fix while you plan a redesign |
5. ObjectProvider | Look the bean up when needed | No | Same as @Lazy, but explicit in code |
6. allow-circular-references=true | Allow early references globally (setter and field injection only) | No, it hides all cycles | Temporary, during an upgrade of a legacy application |
6.1 The @Lazy Workaround
public InventoryService(@Lazy OrderService orders) {
this.orders = orders; // a proxy; the real OrderService is looked up on first call
}
This starts, because Spring injects a proxy that does not need the real bean yet. It also hides the cycle: the classes are still tangled, and a call made during initialization may still fail. See lazy initialization in Spring for how lazy proxies work.
7. A Complete Example: Breaking the Order and Inventory Cycle
The call from inventory to orders is really a notification: "stock arrived for this SKU". That is a perfect fit for an application event. Inventory publishes it and no longer knows that orders exist.
7.1 The Event
package com.javabytechie.shop.inventory;
public record StockReplenished(String sku, int quantity) {
}
7.2 Inventory Publishes Instead of Calling
package com.javabytechie.shop.inventory;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
@Service
public class InventoryService {
private static final Logger log = LoggerFactory.getLogger(InventoryService.class);
private final Map<String, Integer> stock = new ConcurrentHashMap<>(Map.of("KB-100", 1));
private final ApplicationEventPublisher events;
public InventoryService(ApplicationEventPublisher events) {
this.events = events;
}
public boolean reserve(String sku, int quantity) {
int[] reserved = {0};
stock.computeIfPresent(sku, (key, available) -> {
if (available >= quantity) {
reserved[0] = quantity;
return available - quantity;
}
return available;
});
return reserved[0] > 0;
}
public void replenish(String sku, int quantity) {
stock.merge(sku, quantity, Integer::sum);
log.info("Replenished {} x {}", quantity, sku);
events.publishEvent(new StockReplenished(sku, quantity));
}
}
7.3 Orders Depend on Inventory and Listen for the Event
package com.javabytechie.shop.order;
import com.javabytechie.shop.inventory.InventoryService;
import com.javabytechie.shop.inventory.StockReplenished;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Service;
@Service
public class OrderService {
private static final Logger log = LoggerFactory.getLogger(OrderService.class);
private final InventoryService inventory;
private final List<Backorder> backorders = new ArrayList<>();
public OrderService(InventoryService inventory) {
this.inventory = inventory;
}
public synchronized void place(String orderId, String sku, int quantity) {
if (inventory.reserve(sku, quantity)) {
log.info("Order {} confirmed", orderId);
} else {
backorders.add(new Backorder(orderId, sku, quantity));
log.info("Order {} back-ordered", orderId);
}
}
@EventListener
public synchronized void onStockReplenished(StockReplenished event) {
List<Backorder> waiting = backorders.stream().filter(b -> b.sku().equals(event.sku())).toList();
backorders.removeAll(waiting);
waiting.forEach(b -> place(b.orderId(), b.sku(), b.quantity()));
}
record Backorder(String orderId, String sku, int quantity) {
}
}
The dependency now points one way only: OrderService → InventoryService. The event travels the other way without a compile-time or bean dependency.
7.4 Run It
package com.javabytechie.shop;
import com.javabytechie.shop.inventory.InventoryService;
import com.javabytechie.shop.order.OrderService;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
class CycleDemo {
@Bean
ApplicationRunner backorderDemo(OrderService orders, InventoryService inventory) {
return args -> {
orders.place("ORD-1", "KB-100", 1);
orders.place("ORD-2", "KB-100", 1);
inventory.replenish("KB-100", 5);
};
}
}
Started ShopApplication in 1.08 seconds (process running for 1.31)
Order ORD-1 confirmed
Order ORD-2 back-ordered
Replenished 5 x KB-100
Order ORD-2 confirmed
The application starts with the default settings, with no @Lazy and no global switch, and the back-order is retried when stock arrives.
8. Cycles and Proxies: The "Raw Version" Error
If a cycle is allowed and one of the beans is later wrapped in a proxy, for example because it has @Async methods, startup can fail with a different message:
BeanCurrentlyInCreationException: Error creating bean with name 'orderService': Bean with name
'orderService' has been injected into other beans [inventoryService] in its raw version as part
of a circular reference, but has eventually been wrapped.
The other bean received the early reference to the raw object, but the final bean is a proxy, so the two beans would see different objects. The fix is the same: remove the cycle.
9. Catching Cycles in Tests
A context-loading test fails as soon as a cycle appears, as long as you do not enable circular references in test configuration:
package com.javabytechie.shop;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class ShopApplicationTests {
@Test
void contextLoads() {
// fails with BeanCurrentlyInCreationException if a dependency cycle exists
}
}
Keep global lazy initialization off in this test: with spring.main.lazy-initialization=true, beans that are never used are never created, so a cycle among them goes unnoticed.
10. Best Practices
- Use constructor injection so cycles fail at startup instead of hiding.
- Treat a cycle as a design problem, not a configuration problem.
- Turn notifications into events when one side only needs to say "something happened".
- Extract shared logic into a third bean when both classes need the same behavior.
- Use
@Lazyonly as a documented, temporary workaround. - Leave
spring.main.allow-circular-referencesoff in new applications. - Keep a context-loading test so new cycles are caught in CI.
11. Summary
Circular dependencies in Spring occur when beans depend on each other in a loop. With constructor injection, Spring cannot create any bean in the loop and throws BeanCurrentlyInCreationException; with setter or field injection, early references can resolve it, but Spring Boot has prohibited that by default since 2.6. Fix cycles by moving shared logic into a third bean, turning one direction into an event, or passing data instead of beans. Keep @Lazy, ObjectProvider and allow-circular-references as temporary workarounds, and let a context-loading test guard against new cycles.
12. References
Circular Dependencies in Spring Interview Questions and Answers
Common interview questions on Circular Dependencies in Spring, from basic to scenario-based, with short answers you can explain in your own words.
Q. What is a circular dependency, and why is it considered a design smell?
Answer: It is a loop in the bean dependency graph, such as A needs B and B needs A, possibly through several beans. It usually means responsibilities are mixed: two classes share behavior that belongs elsewhere, or one class sends notifications by calling the other directly. It also makes classes impossible to construct or unit test independently.
Q. Why can Spring not resolve a circular dependency that uses constructor injection?
Answer: Each constructor needs a finished reference to the other object, but neither object exists until its own constructor returns. Spring tracks beans that are currently in creation, notices it is asked for one again, and throws BeanCurrentlyInCreationException. With setter or field injection, the constructor can complete first, so an early reference can be handed out.
Q. How does Spring resolve setter-based circular references, and what are early references?
Answer: After instantiating a singleton, Spring registers a factory for an early reference to it in an internal cache. If another bean being created needs it before it is fully initialized, that bean receives the early reference, possibly already wrapped by a post-processor that supports early proxying. Spring keeps three maps for this: finished singletons, early singleton references and singleton factories.
Q. What does spring.main.allow-circular-references do, and why is it false by default?
Answer: It allows Spring to resolve cycles through early references for setter and field injection; it cannot help constructor cycles. Spring Boot 2.6 set it to false because cycles hide design problems and expose partially initialized beans. Setting it to true silences every cycle in the application, so it should only be a short-term measure during migrations.
Q. How does @Lazy break a cycle, and what is the catch?
Answer: @Lazy on an injection point makes Spring inject a proxy instead of the real bean, so creating the bean no longer requires the other one; the proxy resolves the target on the first method call. The catch is that the cycle still exists in the design, a call during initialization may still fail, and the proxy adds indirection that is easy to miss when debugging.
Q. After adding @Async to a method, startup fails with "has been injected into other beans in its raw version". What is going on?
Answer: The bean is part of a circular reference that was resolved with an early reference to the raw object. @Async makes a post-processor wrap the bean in a proxy after initialization, so the final bean differs from the raw reference other beans already hold. Spring refuses to continue because callers would bypass the proxy. Remove the cycle; as a stopgap, injecting with @Lazy avoids the early reference.