Circular dependency in Spring

The Spring reference manual explains how circular dependencies are resolved. The beans are instantiated first, then injected into each other.

Consider this class:

package mypackage;

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;
    }

}

And a similar class B:

package mypackage;

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;
    }

}

If you then had 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>

You would see the following output when creating a context using this configuration:

Creating instance of A
Creating instance of B
Setting property a of B instance
Setting property b of A instance

Note that when a is injected into b, a is not yet fully initialised.

Leave a Comment