Thursday, November 22, 2018
Home > Spring > Depends-on in spring example

Depends-on in spring example

Depends-on in spring example

In this Spring tutorial, we will learn an important feature of spring is depends-on by using this feature we can create an object of any beans before any other beans.

In spring application XML, if we need to initialize or create any bean before any other bean, by using depends-on we can perform this. While initializing bean we need to define a depends-on attribute in the bean.

In the below example, I have explained the working mechanism of depends-on. I have taken three beans A, B, and C.

here A depends on B and B depends on C.

First C will be initialized, and then B and then A.


Example of Depends-on in Spring:

We are using Ecplise IDE and some required jars to develop below application.

Ecplise IDE : Ecplise Luna

Jars: Placed below jar in “Referenced Libraries” Folder

  1. commons-logging-1.2
  2. spring-beans-5.0.8.RELEASE
  3. spring-context-5.0.8.RELEASE
  4. spring-core-5.0.8.RELEASE
  5. spring-expression-5.0.8.RELEASE

To create this example, we have created 5 files inside src directory.

  1. A.java
  2. B.java
  3. C.java
  4. config.xml
  5. Test.java

A.java

package beans;

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

}

B.java

package beans;

public class B {
B()
{
System.out.println("Bean B is initialized");
}

}

C.java

package beans;

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

}

Config.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"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

<!-- bean definitions here -->

<!-- bean A depends on depends on bean B ,hence B object created before A object. -->
<bean id="a" class="beans.A" depends-on="b"/>
<bean id="b" class="beans.B"/>
<bean id="c" class="beans.C"/>

</beans>

Test.java

package test;

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

public class Test {

public static void main(String[] args) {

ApplicationContext context=new ClassPathXmlApplicationContext("resources/config.xml");

}

}

OUTPUT

Bean C is initialized
Bean B is initialized
Bean A is initialized

Related Topics:-

You may also like :-
Admin
We are group of application developer and admin.We are providing good content of information about IT technology and services .

Leave a Reply

Your email address will not be published. Required fields are marked *