DEV Community

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

Posted on • Edited on

3 2

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

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (0)

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay