Wednesday 29 March 2017

Spring: Lazy initialization of beans

By default, application context create and configure all the beans as part of initialization process. If you don't want the bean initialization as part of the initialization process, you can control it by setting the attirbute 'lazy-init' to true.

<bean id="lazyBean" class="com.sample.pojo.A" lazy-init="true"/>
        
Notify above snippet, 'lazyBean' is not initialized unless it called. A lazy-initialized bean tells the IoC container to create a bean instance when it is first requested, rather than at startup.

Following is the complete working application.

A.java
package com.sample.pojo;

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

B.java
package com.sample.pojo;

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

myConfiguration.xml
<?xml version="1.0" encoding="UTF-8"?>
<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="lazyBean" class="com.sample.pojo.A" lazy-init="true"/>

 <bean id="eagerBean" class="com.sample.pojo.B" />

</beans>

HelloWorld.java
package com.sample.test;

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

import com.sample.pojo.A;

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

  System.out.println("Getting the bean of type A");
  
  A lazybean = context.getBean("lazyBean", A.class);

  ((ClassPathXmlApplicationContext) context).close();
 }
}

Run ‘HelloWorld.java’, you can able to see following output.
Bean B is initialized
Getting the bean of type A
Bean A is initialized

Specifying lazy initialization at container level
By setting the attribute 'default-lazy-init' of the element <beans> element to true, you can set the lazy initialization at container level.
<beans default-lazy-init="true">
    <!-- no beans will be pre-instantiated... -->
</beans>




Previous                                                 Next                                                 Home

No comments:

Post a Comment