DEV Community

Cover image for Spring - Circular Dependency
Yiğit Erkal
Yiğit Erkal

Posted on • Updated on

Spring - Circular Dependency

Circular dependencies are the scenarios when two or more beans try to inject each other via constructor.

Bean A → Bean B → Bean C → Bean D → Bean E → Bean A

or in a simpler way

Bean A → Bean B → Bean A

What if everything is 👌

We instead have something like this:

Bean A → Bean B → Bean C

Spring will create bean C, then create bean B (and inject bean C into it), then create bean A (and inject bean B into it).

With a circular dependency, however, Spring is unable to determine which of the beans should be produced first because they are interdependent. Spring will throw a BeanCurrentlyInCreationException while loading context in these circumstances.

When implementing constructor injection in Spring, this can happen. We shouldn't have this problem if we utilize other sorts of injections because dependencies will be injected only when they're needed, not when the context is loaded. ❗

Is there way to fix it? 🤔

  • Redesign (LOL)
  • Use @Lazy Telling Spring to lazy initialize one of the beans is a straightforward method to stop the cycle. As a result, rather than fully initializing the bean, it will generate a proxy that will be injected into the other bean. When the injected bean is first required, it will be fully created.
@Component
public class CircularDependencyA {

    private CircularDependencyB circB;

    @Autowired
    public CircularDependencyA(@Lazy CircularDependencyB circB) {
        this.circB = circB;
    }
}
Enter fullscreen mode Exit fullscreen mode
  • Use Setter/Field Injection Spring creates the beans, but the dependencies are not injected until they are needed in this way

Top comments (0)