java framework_error ai_generated true

org.springframework.beans.factory.BeanCurrentlyInCreationException

ID: java/spring-circular-dependency

Also available as: JSON · Markdown
85%Fix Rate
88%Confidence
65Evidence
2023-01-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
6 active

Root Cause

BeanCurrentlyInCreationException indicates a circular dependency between Spring beans — Bean A depends on Bean B, which depends on Bean A (directly or transitively). Spring Boot 3.x / Spring 6.x no longer allows circular dependencies by default.

generic

Workarounds

  1. 90% success Refactor the circular dependency by extracting shared logic into a third bean that both depend on
    1. Identify the circular chain: A -> B -> A. 2. Extract the shared functionality into a new bean C. 3. Make both A and B depend on C instead of each other. 4. This follows the Dependency Inversion Principle — both beans depend on an abstraction (interface) rather than on each other. 5. Common pattern: extract the shared data access or business logic into a separate service.
  2. 85% success Use event-driven communication between the beans to decouple them
    1. Instead of Bean A calling Bean B directly, have Bean A publish a Spring ApplicationEvent. 2. Bean B listens for the event with @EventListener. 3. This removes the direct dependency: A no longer needs a reference to B. 4. For synchronous behavior, use @EventListener. For async, use @Async @EventListener. 5. Alternatively, use an interface + injection: Bean A depends on an interface that Bean B implements, and inject via setter or @PostConstruct instead of constructor.

Dead Ends

Common approaches that don't work:

  1. Setting spring.main.allow-circular-references=true to re-enable the deprecated behavior 60% fail

    This property was added as a migration aid for Spring Boot 3.x. Enabling it masks a design problem. Circular dependencies make the initialization order undefined, can cause partially initialized beans to be injected, and make the application fragile and hard to test.

  2. Using @Lazy on one of the circular dependencies as a permanent solution 55% fail

    @Lazy creates a proxy that defers initialization, breaking the cycle at startup. However, the circular dependency still exists in the design. The lazy proxy can cause unexpected behavior: the real bean is created on first access, which can happen at unpredictable times, potentially causing threading issues or startup order problems.

Error Chain

Leads to:
Preceded by:
Frequently confused with: