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"?>
<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">
<bean id="a" class="dependency.A">
</bean>
<bean id="b" class="dependency.B">
<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
<?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">
<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>
The output will be
Output 2
A
C
B