Consider the following code:
Here is class A
public class A {
public A() {
System.out.println("Creating instance of A");
}
private B b;
public void setB(B b) {
System.out.println("Setting property b of A instance");
this.b = b;
}
}
Here is class B
public class B {
public B() {
System.out.println("Creating instance of B");
}
private A a;
public void setA(A a) {
System.out.println("Setting property a of B instance");
this.a = a;
}
}
We have this configuration file:
<bean id="a" class="mypackage.A">
<property name="b" ref="b" />
</bean>
<bean id="b" class="mypackage.B">
<property name="a" ref="a" />
</bean>
Output:
Creating instance of A
Creating instance of B
Setting property a of B instance
Setting property b of A instance
when a
is injected into b
, a
is not yet fully initialized.
My question:
Even though 'a' is not fully initialized when 'b' gets reference to 'a' , but after few moments 'a' will be completely initialized. Since 'b' has a reference to 'a', then 'b' will be pointing to fully initialized 'a' after few moments.
This explanation is generally given to show disadvantage of circular dependency.
But in the end we have a normal situation of both fully initialized beans 'a' and 'b' pointing to each other. Hence, how does this example show us disadvantage of using circular dependency ?
I would quote from spring docs:
Unlike the typical case (with no circular dependencies), a circular dependency between bean A and bean B forces one of the beans to be injected into the other prior to being fully initialized itself (a classic chicken/egg scenario)
Reference : Example taken from Circular dependency in spring