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


package beans;

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



package beans;

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



package beans;

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



<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
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"/>



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");




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

Related Topics:-

You may also like :-
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 *