Spring Lazy-Init With Example

Spring Lazy-Init With Example

In Spring ,ApplicationContext implementations eagerly instantiates all singleton beans. we can prevent pre-instantiation of a singleton bean by marking the bean definition as lazy-initialized. by making lazy-initialized of spring beans Ioc Container will not create instance immediately at loading of spring configuration file. lazy-initialized spring bean suggests the spring(IOC) container to create a bean instance when it is first requested, rather than at startup. We can do this by adding lazy-init attribute to bean tag. lazy-int attribute has two values trueand false if the valueof lazy-init is truea bean instance wll be created when it is made first request to bean. if the valueof lazy-init is falsea bean instance wll be created when Ioc Container start up.

add lazy -init attribute to <bean> tag like following.

<bean id="demoBean1" class="com.practice.DemoBean1" lazy-init = "true" >
</bean >

Lets See Complete example

Tools Used In This Article

  • Spring 4.3.2
  • Maven 4.0.0
  • JDK 1.6

First create Maven Project from the Ecclipse and below is Project Directory Structure

Project Structure

Maven Dependencies

Add The Following Dependencies to the pom.xml

  • spring-core
  • spring-beans
  • spring-context


<project xmlns="http://maven.apache.org/POM/4.0.0"




Next Step is Writing Spring Beans


package com.practice;

public class DemoBean1 {

public DemoBean1() {
System.out.println("Pre-instantiaion of DemoBea1");



package com.practice;

public class DemoBean2 {

public DemoBean2() {
System.out.println("Lazy-instantiation of DemoBean2");


Now prepare spring configuration file


<beans xmlns="http://www.springframework.org/schema/beans"
<bean id="demoBean1" class="com.practice.DemoBean1" lazy-init = "false">


<bean id="demoBean2" class="com.practice.DemoBean2" lazy-init = "true">



Create Test class And Run the code


package com.java2study;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.practice.DemoBean2;

public class Test {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

DemoBean2 demoBean2 = (DemoBean2)context.getBean("demoBean2");



INFO: Loading XML bean definitions from class path resource [applicationContext.xml]
Pre-instantiaion of DemoBea1
Lazy-instantiation of DemoBean2