Logo

dev-resources.site

for different kinds of informations.

Circular ⭕ dependency exceptions in Spring❗

Published at
6/21/2023
Categories
spring
springboot
java
exception
Author
MAYUR KUMBHAR
Categories
4 categories in total
spring
open
springboot
open
java
open
exception
open
Circular ⭕ dependency exceptions in Spring❗

Issue?

When two beans are waiting for each other to be created in the spring context so that autowiring can happen, this state is called as Circular Dependency and we get the BeanCurrentlyInCreationException exception.

Scenario, lets say BeanA is defined as below

@Component 
class BeanA{

@Autowired // here BeanA is depends on BeanB
public BeanB bean;

}

Now lets say we have BeanB as below

@Component 
class BeanB{

@Autowired // here BeanB is depending on BeanA
public BeanA bean;

}

So there is dependency between two components resulting in circular dependency as each bean is waiting for its dependent bean to created for autowiring.

Solution

Developer should be careful while creating the Beans, making sure there are no circular dependency. But is worst case if there exists case or by mistake some developer put the circular dependency then we can follow below to resolve this.

Use setter injection instead of constructor injection

We can use the setter injection in one of class for dependent bean, so that injection is happed after one object is created avoiding the race condition.

Use Lazy initialization on beans

We can use @Lazy annotation on one of the bean in circular dependency so that one of bean creation is delayed until bean is actually required.

Refactor code to remove circular dependency

We should avoid creating such circular dependency in first place, and refactor code respectively to remove the circular dependency.

Featured ones: