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
BeanB.java
beancontext.xml
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
OUTPUT:
When we run DependsDemo class we will get the below output
As we can see in the output,spring container initialized the BeanB first and then the BeanA.
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
BeanB.java
beancontext.xml
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
OUTPUT:
When we run DependsDemo class we will get the below output
As we can see in the output,spring container initialized the BeanB first and then the BeanA.
No comments:
Post a Comment