Home  >  Spring

Spring lazy-init Example

By Arvind Rai, November 05, 2021
Spring ApplicationContext creates a bean with singleton scope by default. Generally singleton beans are pre-initialized. This is because errors in the configuration or surrounding environment can be discovered immediately. If this behavior is not desired and we want to initialize singleton bean lazily, we can use lazy-init attribute on the <bean> element. The lazy-init accepts boolean value. The lazy-init="true" enables a bean to be loaded lazily.
Find the sample code snippet.
<bean id="myBean" class="com.concretepage.MyBean" lazy-init="true"/> 




Using lazy-init

app-conf.xml
<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.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 

Reference

Lazy-initialized Beans
POSTED BY
ARVIND RAI
ARVIND RAI











©2021 concretepage.com | Privacy Policy | Contact Us