00:00

Circular Dependencies in Spring

Last updated:

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.

Analogy: Two new employees each refuse to start until the other has finished onboarding. Nobody can go first, so nobody ever starts. The fix is not to make one of them start half-trained; it is to change how the work is split.

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:

OrderService.java (cyclic)
@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
    }
}
InventoryService.java (cyclic)
@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:

Console
***************************
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

Why a constructor injection cycle cannot be createdTo create OrderService, Spring must call its constructor with an InventoryService, so it starts creating InventoryService. Its constructor needs an OrderService, which is currently in creation and has no instance yet, because its own constructor has not returned. Spring detects the bean already in creation and throws BeanCurrentlyInCreationException. Create orderService constructor needs InventoryService Create inventoryService constructor needs OrderService 1. start creating inventoryService 2. orderService is "currently in creation" BeanCurrentlyInCreationException no instance exists yet to hand over
Each constructor waits for the other's object, which cannot exist until its own constructor returns.

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:

  1. Call OrderService's constructor. The object exists but has no dependencies yet.
  2. 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).
  3. Inject dependencies into OrderService: create InventoryService, whose setter asks for OrderService and receives the early reference.
  4. Finish InventoryService, then finish OrderService.

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:

FixHowImproves design?Use when
1. Move the shared logicExtract the code both classes need into a third beanYesTwo classes share a responsibility
2. Reverse one direction with eventsOne side publishes an event; the other listensYesOne call is a notification ("something happened")
3. Pass data instead of the beanGive the method the values it needs as argumentsYesOne class only reads data from the other
4. @Lazy on one injection pointSpring injects a lazy proxy that resolves the real bean on first useNoA quick, local fix while you plan a redesign
5. ObjectProviderLook the bean up when neededNoSame as @Lazy, but explicit in code
6. allow-circular-references=trueAllow early references globally (setter and field injection only)No, it hides all cyclesTemporary, during an upgrade of a legacy application

6.1 The @Lazy Workaround

InventoryService.java (@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

StockReplenished.java
package com.javabytechie.shop.inventory;

public record StockReplenished(String sku, int quantity) {
}

7.2 Inventory Publishes Instead of Calling

InventoryService.java
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

OrderService.java
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

CycleDemo.java
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);
        };
    }
}
Console
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:

Console
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:

ShopApplicationTests.java
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 @Lazy only as a documented, temporary workaround.
  • Leave spring.main.allow-circular-references off 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