Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to resolve circular dependency between beans in Spring IoC? [duplicate]

Tags:

java

spring

Suppose I have a bean which depends on another bean, and another bean depends on first bean.

Bean#1 -> Bean#2 -> Bean#1

How can I resolve this issue?

like image 481
Alex Avatar asked Dec 09 '22 06:12

Alex


1 Answers

This is from Spring Reference

You can generally trust Spring to do the right thing. It detects configuration problems, such as references to non-existent beans and circular dependencies, at container load-time. Spring sets properties and resolves dependencies as late as possible, when the bean is actually created.

So it instantiates both beans and injects them onto each other.

EDIT

In your case BeanCurrentlyInCreationException mostly arose due to constructor injection. If that is the case mostly using setter injection instead of constructor injection will solve the issue. Constructor injection typically gives rise to the chicken-egg problem!

like image 195
Abhiroop Sarkar Avatar answered Dec 11 '22 07:12

Abhiroop Sarkar