Skip to content
Latchkey

Spring "The dependencies of some of the beans form a cycle" - Fix in CI

Spring found a dependency cycle: bean A needs bean B and bean B needs bean A. With constructor injection (and circular references disabled by default since Spring Boot 2.6) the container cannot instantiate either first.

What this error means

Startup fails with The dependencies of some of the beans in the application context form a cycle: followed by a diagram of the loop, or BeanCurrentlyInCreationException: ... requested bean is currently in creation: Is there an unresolvable circular reference?

java
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]
      |
   orderService (again)

Common causes

Two beans constructor-inject each other

A direct A -> B -> A constructor cycle cannot be resolved because neither bean can be fully built before the other.

A longer cycle through several beans

The loop may span three or more beans; the diagram in the error lists every node in the cycle.

Circular references are disabled by default

Since Spring Boot 2.6 spring.main.allow-circular-references defaults to false, so cycles that older apps tolerated now fail startup.

How to fix it

Break the cycle by extracting a third bean

Move the shared behavior into a new collaborator both beans depend on, removing the back-edge. This is the correct structural fix.

Java
// Instead of OrderService <-> InventoryService, both depend on StockLedger
class OrderService { OrderService(StockLedger ledger) { } }
class InventoryService { InventoryService(StockLedger ledger) { } }

Use @Lazy on one injection point

Defer one side so a proxy is injected and the real bean is created on first use, breaking the construction-time loop.

Java
class OrderService {
  OrderService(@Lazy InventoryService inventory) { /* ... */ }
}

Last resort: allow circular references

Re-enable the legacy behavior only to unblock; treat it as debt, not a fix.

yaml
# application.yml
spring:
  main:
    allow-circular-references: true

How to prevent it

  • Favor constructor injection and small, single-responsibility beans.
  • Extract shared logic into its own bean instead of cross-wiring services.
  • Keep allow-circular-references at its secure default (false) so cycles fail in CI.

Related guides

Tired of flaky CI? Latchkey auto-heals failed jobs and retries them for you. Start free →