Home  >  Spring Core

Example of lazy-init in Spring

By Arvind Rai, April 13, 2013
lazy-init in spring is the attribute of bean tag. The values of lazy-init are true and false. If lazy-init is true, then that bean will be initialized when a request is made to bean. This bean will not be initialized when the spring container is initialized. If lazy-init is false then the bean will be initialized with the spring container initialization and this is the default behavior.
app-conf.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">
     
    <bean id="testA" class="com.concretepage.A"/>
    <bean id="testB" class="com.concretepage.B" lazy-init="true"/>
</beans> 




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

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

SpringTest.java
package com.concretepage;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringTest {
	public static void main(String[] args) {
		 ApplicationContext context = new ClassPathXmlApplicationContext("app-conf.xml");
		 System.out.println("Feth bean B.");
		 context.getBean("testB");
	}
} 

Output
Bean A is initialized
Feth bean B.
Bean B is initialized 
Find the link for annotation Example of @Lazy in Spring
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us