Skip to main content
Chapter 12 of 18 · 3 sections

Spring: Lazy Initialization

Delay bean creation with XML or annotations and understand eager dependency resolution.

Original chapter: Spring Lazy Initialization. The text and examples below are preserved from the historical source; read the corrections above before using them.

Section 12.1: Example of Lazy Init in Spring

The @Lazy allow us to instruct the IOC container to delay the initialization of a bean. By default, beans are instantiated as soon as the IOC container is created, The @Lazy allow us to change this instantiation process.

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

Source example · PDF page 53
<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"/>

A.java

Source example · PDF page 53
package com.concretepage;
public class A {
public A(){
   System.out.println("Bean A is initialized");
  }
}

B.java

Source example · PDF page 53
package com.concretepage;
public class B {
public B(){
   System.out.println("Bean B is initialized");
  }
}

SpringTest.java

Source example · PDF page 53
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

Source example · PDF page 54
Bean A is initialized
Feth bean B.
Bean B is initialized

Section 12.2: For component scanning and auto-wiring

Source example · PDF page 54
@Component
@Lazy
public class Demo {
   ....
   ....
}

@Component
public class B {

   @Autowired
   @Lazy // If this is not here, Demo will still get eagerly instantiated to satisfy this request.
   private Demo demo;

   .......
}

Section 12.3: Lazy initialization in the configuration class

Source example · PDF page 54
@Configuration
// @Lazy - For all Beans to load lazily
public class AppConf {

   @Bean
   @Lazy
   public Demo demo() {
       return new Demo();
   }
}
Buy me a coffee
Daily Practice
0/0