Share on Google+Share on Google+

Spring Lazy Initialization, Spring Lazy Loading example

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.

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) { = city;

  public String getState() {
    return state;

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


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) { = name;

package lazyinitialized.bean.example;

import org.springframework.beans.factory.BeanFactory;

public class LazyInitMain {

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

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""

  <bean id="studentBean" class="lazyinitialized.bean.example.Student">
    <property name="name" value="satya"/>
  <bean id="addressBean" class="lazyinitialized.bean.example.Address"
    <property name="city" value="New Delhi" />
    <property name="state" value="Delhi"/>


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



Posted on: August 23, 2010 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.


Advertisement null