In this tutorial, we are going to learn about what is Spring circular dependency problem ? and how to resolve it.

What is circular dependency ?

In our day to day development life, while implementing the spring applications, we may have a requirement like : class A  depending on class B  and class B also depending on class A, however this is not a good practice to program, depending 2 classes on each other, though it is not a good practice some times we can’t avoid such time of handling.

Spring considers this type of scenario as circular dependency, and it also given some good practices to handle this. Here we are going to discuss, how do we handle this kind of scenarios.

Where we get circular dependency problem :

In spring we have different types of dependency injections, if we inject the dependency through the constructor arguments <constructor-arg>, and the two classes are depending on each other then spring will throw an exception like BeanCurrentlyInCreationException, this is where we get circular dependency in spring.

 

In case of constructor injection, the dependencies are injected while creating the object, so that, by the time creating the object of A, there is no B object and vice versa.

Example :

class A {
    private B b;
    public A(B b) {
        this.b = b;
    }
}

class B {
    private A a;
    public B(A a) {
        this.a = a;
    }
}

 

On the above, while creating the object A, object of B is required. Similarly to create an object for B, object A is required. Finally A & B both objects are not created, and an exception will be thrown by spring container.

How to solve the circular dependency ?

In order to solve the circular dependency problem at one side, the dependency injection type must be change to setter injection.

In case of setter injection, the dependencies are injected after creating the object, but not while creating the objects.

Example :

class A {
    private B b;
    public void setB(B b) {
        this.b = b;
    }
}

class B {
    private A a;
    public void setA(A a) {
        this.a = a;
    }
}

In the above, Spring container will injects object of class B to A like following.

A a = new A();

B b = new B();

a.setB(b);

Happy Learning 🙂