Spring Lazy Initialization, Spring Lazy Loading example


 

Spring Lazy Initialization, Spring Lazy Loading example

In this tutorial you will learn about the Spring Lazy Initialization in the spring framework.

In this tutorial you will learn about the Spring Lazy Initialization in the spring framework.

Spring Lazy Initialization

In general all bean are initialized at startup. To stop such unnecessary initialization we use lazy initialization which create the bean instance when it if first requested

The lazy-init attribute are defined in the xml file at the <bean/> element.

Address.java

package lazyinitialized.bean.example;

public class Address {
  public Address() {
    System.out.println("Inside Address Constructor");
  }

  private String city;
  private String state;

  public String getCity() {
    return city;
  }

  public void setCity(String city) {
    this.city = city;
  }

  public String getState() {
    return state;
  }

  public void setState(String state) {
    this.state = state;
  }

}

Student.java

package lazyinitialized.bean.example;

public class Student {
    private String name;
    private Address address;
    
    public Student(){
        System.out.println("Inside Student Constructor");
    }

    public Address getAddress() {
        return address;
    }

    public void setAddress(Address address) {
        this.address = address;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }    
}

LazyInitMain.java

package lazyinitialized.bean.example;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class LazyInitMain {

  public static void main(String args[]) {
    BeanFactory beanfactory = new ClassPathXmlApplicationContext(
    "context.xml");
    System.out.println("Initialization done when require");
    beanfactory.getBean("addressBean");
  }
}

context.java

<?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="studentBean" class="lazyinitialized.bean.example.Student">
    <property name="name" value="satya"/>
        
  </bean>
  <bean id="addressBean" class="lazyinitialized.bean.example.Address"
    lazy-init="true">
    <property name="city" value="New Delhi" />
    <property name="state" value="Delhi"/>
  </bean>

</beans>

When you run this application it will display output as shown below:


Inside Student Constructor
Initialization done when require
Inside Address Constructor

Download this example code

Ads