Spring depends-on attribute

When Spring loads the application context, it creates the beans following its own particular order.

Irrespective of the order in which it creates the beans, it makes sure that a bean’s dependency (which are other beans) are set before the beans is ready of use.

Below code will give you an example of what I am saying.

A Class


package dependency;

public class A {
    public A() {
        System.out.println("A");
    }
}

C class


package dependency;

public class C {
    public C() {
        System.out.println("C");
    }
}

B class


package dependency;

public class B {
    private A a;
    private C c;
    
    public B() {
        System.out.println("B");
    }

    public A getA() {
        return a;
    }

    public void setA(A a) {
        this.a = a;
    }

    public C getC() {
        return c;
    }

    public void setC(C c) {
        this.c = c;
    }
}

Spring Configuration

<?xml version=”1.0″ encoding=”UTF-8″?><?xml version=”1.0″ encoding=”UTF-8″?><beans xmlns=”http://www.springframework.org/schema/beans” xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”xmlns:aop=”http://www.springframework.org/schema/aop”xsi:schemaLocation=”http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd”&gt; <bean id=”a” class=”dependency.A”> </bean> <bean id=”b” class=”dependency.B” depends-on=”a, c”> <property name=”a” ref=”a”/> <property name=”c” ref=”c”/> </bean> <bean id=”c” class=”dependency.C”> </bean></beans>

From the above code Class B depends on Class A and Class C.

So when the application context is loaded in the main class

Main Class


package dependency;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class DependencyDemo1 {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("depedency.xml");
    }
}

The output will be

Output 1

A
B
C

From the output even though B is dependent on C. C is created after B and set to B.

We can force the order of bean instantiation using the depends-on attribute.

Since B depends on A and C, we put the attribute in B’s bean definition as shown below

<bean id=”b” class=”dependency.B” depends-on=”a, c”><bean id=”b” class=”dependency.B” depends-on=”a, c”> <property name=”a” ref=”a”/> <property name=”c” ref=”c”/></bean>

The output will be

Output 2

A
C
B

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s