Searching...
Tuesday, 13 August 2013

Spring bean initialization dependency Example

02:20

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 (First.java and Second.java)

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="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-2.5.xsd">

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

Create a main class to test bean initialization

package com.vinod.spring.test;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MySpringMain {

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

    }

}
 

Output

Class Second Initialized
Class First is initialized

 

0 comments: