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 asCircular Dependency and we get theBeanCurrentlyInCreationException
exception.
Scenario, lets say BeanA is defined as below
@ComponentclassBeanA{@Autowired// here BeanA is depends on BeanBpublicBeanBbean;}
Now lets say we have BeanB as below
@ComponentclassBeanB{@Autowired// here BeanB is depending on BeanApublicBeanAbean;}
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.
Top comments(0)
For further actions, you may consider blocking this person and/orreporting abuse