Skip to content
javahacks.dev
Spring Boot

Fix Spring Boot Circular Dependency Errors Step by Step

Break the circular dependency Spring Boot refuses to start with by extracting a third bean, publishing an event or, as a last resort, using lazy injection.

6 min read
Summarize in AI
Flat illustration of a start button surrounded by Spring Boot starters, with the Spring Boot, Spring, Gradle and Spring Security logos.

When Spring Boot refuses to start with a message about a circular reference, it is reporting a real design problem, not a configuration glitch. Bean A needs B to be constructed, and B needs A, so neither can be built first. This post shows how to read the report, which edge of the cycle to cut, and three fixes in order of preference. It ends with the setting that turns the check off and why you should leave it alone. It applies to Spring Boot 3 and 4 on JDK 25.

Read the cycle, then pick an edge to cut

The startup failure prints the cycle in order:

Text
***************************
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:

Despite circular references being allowed in the past, they are prohibited by default.
Update your application to remove the dependency cycle between beans.

Spring Framework used to resolve some cycles by handing out a half-built bean through field or setter injection. Boot 2.6 turned that off by default, because it hid design problems and produced objects that were used before they were fully initialised. With constructor injection, which is the recommended style, a cycle cannot be satisfied at all, and the container reports it immediately. The related exception, when the cycle is found at runtime, is described in BeanCurrentlyInCreationException, and the container mechanics behind it are in how the Spring container works.

A cycle with two beans is usually a design error. A cycle with five is more often an accumulation of convenience calls. Either way, the report tells you where to look, and the cheapest edge to remove is the one your code uses least. Find the method in InventoryService that calls back into OrderService, and ask what it needs.

Fix 1: extract a third bean

Most cycles exist because two services share a piece of logic and each calls the other to reach it. Pull the shared piece into a new bean that both depend on.

src/main/java/com/example/orders/OrderService.javajava
@Service
class OrderService {

    private final StockLevels stock;

    OrderService(StockLevels stock) { this.stock = stock; }

    void place(Order order) {
        stock.reserve(order.sku(), order.quantity());
        // ...
    }
}

@Service
class InventoryService {

    private final StockLevels stock;

    InventoryService(StockLevels stock) { this.stock = stock; }
}

StockLevels owns the stock data and the reservation rules, and depends on neither service. The dependency graph is now a tree: two services point at one component. It is also easier to test, since StockLevels can be faked in one place. When you cannot name the extracted bean in a few words, the two services probably share a concept you have not named yet. Naming it is the real fix.

Fix 2: publish an event

If InventoryService calls OrderService only to say "stock changed, you may want to react", invert the dependency with an application event.

java
@Service
class InventoryService {

    private final ApplicationEventPublisher events;

    InventoryService(ApplicationEventPublisher events) { this.events = events; }

    void adjust(String sku, int delta) {
        // update stock
        events.publishEvent(new StockChanged(sku, delta));
    }
}

@Service
class OrderService {

    @EventListener
    void on(StockChanged event) { /* retry backordered lines */ }
}

InventoryService no longer knows that OrderService exists. The cost is indirection: a reader looking at adjust cannot see who reacts, and a listener failure is by default thrown back through the publisher. Use @TransactionalEventListener when the reaction must wait for the commit. Events suit notifications, not calls that need a return value.

Fix 3: split by use case

A service that has grown to fifteen methods often depends on others for only a few of them. UserService calls OrderService to count orders, and OrderService calls UserService to load the customer. Split each into the part that others use and the part that coordinates:

UserLookup and OrderQueries are small and depend only on repositories. UserService and OrderService use them freely, and nothing points back. This resembles the third bean fix, but the motive differs: you are cutting the class along the lines of its callers.

Last resort: @Lazy

java
OrderService(@Lazy InventoryService inventory) { this.inventory = inventory; }

@Lazy on an injection point makes Spring inject a proxy and build the real bean on first use, which breaks the cycle at startup. It works, and it moves the failure: the cycle still exists, a bean is used through a proxy, and an initialisation-order bug can now appear at runtime on the first call. Keep it for the cases where you cannot restructure, such as a third-party configuration class, and leave a comment with the reason and a ticket.

A cycle that hides in configuration classes

Not every cycle is between services. A @Configuration class that injects a bean defined in another configuration class which, in turn, injects something from the first, produces the same report with names like securityConfig and userDetailsConfig. The usual culprit is Spring Security: a PasswordEncoder bean declared in the same class as the filter chain, which needs a service that needs the encoder. Declare shared infrastructure beans such as encoders and clocks in a small configuration class of their own, with no dependencies, so that everything else can depend on it freely.

Static @Bean methods are another tool for this. A static factory method for a BeanPostProcessor or a PasswordEncoder does not require the enclosing configuration class to be instantiated first, which removes the cycle through the configuration object itself. Look at the cycle report for the word Configuration before you start restructuring services.

The setting that turns the check off

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

This restores the pre-2.6 behaviour for setter and field injection. It does not help constructor injection. It also lets partially initialised beans escape, which leads to NullPointerException in code that runs during startup, and to proxies that are missing because one bean was injected before its post-processors ran. Teams turn it on to get a build through a deadline and keep it for years. If you inherit an application with it on, remove the property in a branch, list every cycle the report shows and fix them one at a time. The general startup failures are catalogued in application failed to start.

How to choose between the three fixes

Ask what the dependency is for. If both beans need the same data or rule, extract it. If one bean only wants to be told that something happened, publish an event. If the two beans are really one concept that grew in two directions, merge or re-split them along use cases. The @Lazy shortcut is for the case where none of those is possible this week. Whichever fix you choose, run the application's tests afterwards, because a changed construction order can expose initialisation code that relied on the old one.

Prevent the next one

An ArchUnit test can fail the build when packages depend on each other in a loop, and catches design cycles before they become bean cycles:

java
@AnalyzeClasses(packages = "com.example")
class ArchitectureTest {
    @ArchTest
    static final ArchRule no_package_cycles =
        slices().matching("com.example.(*)..").should().beFreeOfCycles();
}

This is stricter than Spring's check, since it flags package cycles that Spring would tolerate. Introduce it on a new codebase, and on an old one start with the slices that matter.

Where it does not apply

Cycles between objects that are not Spring beans, such as a parent and its child entities, are normal. The error concerns construction order only. The injection rules are in the Spring reference on dependencies, and the Boot behaviour is in the Boot reference.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.