In this tutorial, we are going to learn about what is Spring circular dependency problem? and how to resolve it.
What is a 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
, though it is not a good practice sometimes you can’t avoid such types of dependencies.
Spring considers this type of scenario as a circular dependency and is also given some good practices to handle this. Here, I am going to show you the most popular way to handle this scenario.
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 the 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 object of B
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 object A
, object B
is required. Similarly to create an object for B
, object A
is required. Finally, A and B objects will not be created as these two are depends on each other and an exception will be thrown by the spring container.
How to solve the circular dependency?
In order to solve the circular dependency problem on one side, the dependency injection type must be changed to setter injection. In the case of setter injection, the dependencies are injected after creating the object, 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, the Spring container will inject objects of class B to A, like the following.
A a = new A();
B b = new B();
a.setB(b);
References:
Happy Learning 🙂