BackendBench
Coffee

Home โ€บ Java exceptions โ€บ BeanCurrentlyInCreationException

Unchecked exception ยท org.springframework.beans.factory

BeanCurrentlyInCreationException: causes and fixes

Two or more beans depend on each other, forming a circular dependency that Spring cannot resolve.

What it looks like

org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'orderService': Requested bean is currently in creation: Is there an unresolvable circular reference?

Extends BeanCreationException in org.springframework.beans.factory.

What it means

With constructor injection, bean A needs B to be built, and B needs A, so neither can be created first. Since Spring Boot 2.6 circular references are prohibited by default, and the startup failure prints the cycle as a diagram: A (by constructor) to B (by constructor) back to A. Older versions silently resolved field-injected cycles with early references, which hid a design problem.

Common causes

How to fix it

  1. Break the cycle by extracting the shared logic into a third bean that both depend on.
  2. Replace one direction with an event (ApplicationEventPublisher) so the dependency is not direct.
  3. Inject lazily as a last resort with @Lazy on one constructor parameter.
  4. Avoid spring.main.allow-circular-references=true, which only hides the design problem.

Broken and fixed

fails
@Service class A { A(B b) {} }
@Service class B { B(A a) {} }
works
@Service class A { A(Shared s) {} }
@Service class B { B(Shared s) {} }
@Service class Shared { }

๐Ÿ”Ž Unravel the failing code ๐Ÿ”Ž Unravel the fix

Debug it faster

Paste the whole stack trace into the stack trace beautifier to hide framework frames, jump to the root cause and find the first line of your own code. It runs in your browser, so the trace never leaves your machine.

Frequently asked questions

Is BeanCurrentlyInCreationException a checked or unchecked exception?

BeanCurrentlyInCreationException is an unchecked exception (it extends BeanCreationException, which is a RuntimeException), so you are not forced to catch it. Prevent it with validation, or handle it where the input enters the system.

Which package is BeanCurrentlyInCreationException in?

It lives in org.springframework.beans.factory, so the import is import org.springframework.beans.factory.BeanCurrentlyInCreationException;.

What is the first thing to check when I see BeanCurrentlyInCreationException?

Read the message and the first stack trace line in your own code. The usual causes are: Two services that call each other directly through constructor injection; and A configuration class that injects a bean defined by itself indirectly.

Related exceptions

More tools you might need