Searching...
Tuesday, 13 August 2013

Spring lazy-init Example

01:56

lazy-init is the same concept of lazy loading and it is one of the attribute of bean, either this can be true or false.In this example we are going to test both scenarios
lazy-init=true (Bean will initialized when a request is received)
lazy-init=false(Bean will initialized with spring container initialization

1. Create two sample beans (First.java, Second.java)

package com.pretech; 
public class First { 
	public First() {
		System.out.println("Class First is initialized");
	}
}
package com.pretech; 
public class Second { 
	public Second() {
		System.out.println("Class Second Initialized");
	} 
}

Create spring configuration xml file with lazy-init attribute (spring-lazy.xml)

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">
<beanid="first"class="com.pretech.First"lazy-init="false"/>
<beanid="second"class="com.pretech.Second"lazy-init="true"/>
</beans>

Create a Main class to test lazy-init

package com.pretech; 
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; 
public class SpringLazyInitTest { 
	public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext("spring-lazy.xml");
		System.out.println("Calling Second Bean");
		context.getBean("second");
	} 
}

Output


Below output we can see class First is initialized during Spring container start up and Class second is initialized upon the the request

Class First is initialized
Calling Second Bean
Class Second Initialized

0 comments: