Ad

Wednesday 25 March 2015

depends-on attribute in spring with an example

In this post we will see the usage of depends-on attribute in spring.In spring if a bean has a dependency on another bean,we will declare one bean as the property of the other.But however in some cases the dependency will be indirect i.e we want a bean to be initialize only after a certain bean is initialized.depends-on attribute is used in this case. Below code example will explain this in detail.

BeanA,BeanB - Spring bean classes.Here we want the Spring container to initialize BeanB first and then the BeanA.
DependsDemo -  Main class which load the container and initializes the bean.
beancontext.xml - metadata configuration details for the spring container.

BeanA.java

package test;

public class BeanA {

private String id;

public BeanA(String id) {
this.id = id;
System.out.println("BeanA created::id=" + this.id);
}

public String getId() {
return id;
}

}

BeanB.java

package test;

public class BeanB {

private String id;

public BeanB(String id) {
this.id = id;
System.out.println("BeanB created::id=" + this.id);
}

public String getId() {
return id;
}

public void setId(String id) {
this.id = id;
}
}


beancontext.xml

<?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.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">

<bean id="beanA" class="test.BeanA" depends-on="beanB">
<constructor-arg  name="id" value="A01"/>
</bean>

<bean id="beanB" class="test.BeanB">
<constructor-arg  name="id" value="B01"/>
</bean>

</beans>


As we can see in the application context file,in the bean definition of BeanA we used depends-on attribute to specify its dependency on BeanB.Hence the spring container will initialize the BeanB first and then the bean BeanA.

DependsDemo.java

package test;

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

public class DependsDemo {

public static void main(String[] args) {
System.out.println("Initilaizing the container::");
ApplicationContext bf = new ClassPathXmlApplicationContext(
new String[] { "beancontext.xml" });
}

}

OUTPUT:

When we run DependsDemo class we will get the below output

Initilaizing the container::
BeanB created::id=B01
BeanA created::id=A01

As we can see in the output,spring container initialized the BeanB first and then the BeanA.

No comments:

Post a Comment