Tuesday, 13 August 2013

Spring bean initialization dependency Example


During the spring bean initialization if we want to initialize any bean before any other bean we can use depends-on attribute in bean configuration xml.
In the below example class fist is depends on class second so class second should initialize prior to class fist.

Create two java beans ( and

package com.vinod.spring.test;

public class First {
    public First() {
        System.out.println("Class First is initialized");

package com.vinod.spring.test;

public class Second {
    public Second() {
        System.out.println("Class Second Initialized");

Update depends-on attribute in spring bean configuration 

<beans xmlns=""

    <bean id = "first" class="com.vinod.spring.test.First" depends-on="second"/>
    <bean id = "second" class="com.vinod.spring.test.Second" />

Create a main class to test bean initialization

package com.vinod.spring.test;


public class MySpringMain {

    public static void main(String[] args) {
        new ClassPathXmlApplicationContext("applicationcontext.xml");




Class Second Initialized
Class First is initialized