tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Interviews | Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 Spring > Core > Lazy Bean

Lazy Bean 

Spring Inversion of Control (IoC) also known as Dependency Injection (DI) is a process by which objects define their dependencies with collaborating objects. The following example shows a lazy initialized bean. The first bean (lazy1) being singleton is initialized during ApplicationContext initialization. Though the second bean (lazy2) is singleton it is not initialized as part of ApplicationContext initialization because its lazy-init attribute is set to true.

File Name  :  
/SpringCore001/conf/lazy/lazy_basic.xml 

File Name  :  
com/bethecoder/tutorials/spring3/basic/LazyBean.java 
   
package com.bethecoder.tutorials.spring3.basic;

public class LazyBean {

  public LazyBean(String name) {
    System.out.println("In Constructor : " + name);
  }
}
   

File Name  :  
com/bethecoder/tutorials/spring3/tests/lazy/BasicTests.java 
Author  :  Sudhakar KV
Email  :  [email protected]
   
package com.bethecoder.tutorials.spring3.tests.lazy;

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

import com.bethecoder.tutorials.spring3.basic.LazyBean;

public class BasicTests {

  /**
   @param args
   */
  public static void main(String[] args) {
    
    System.out.println("Initializing ApplicationContext");
    ApplicationContext factory = new ClassPathXmlApplicationContext("lazy_basic.xml");
    System.out.println("ApplicationContext Initialized");
    
    System.out.println("Accessing lazy1");
    LazyBean lazy1 = (LazyBeanfactory.getBean("lazy1");
    System.out.println(lazy1);

    System.out.println("Accessing lazy2");
    LazyBean lazy2 = (LazyBeanfactory.getBean("lazy2");
    System.out.println(lazy2);
  }

}
   

It gives the following output,
Initializing ApplicationContext
In Constructor : Non Lazy
ApplicationContext Initialized

Accessing lazy1
com.bethecoder.tutorials.spring3.basic.LazyBean@db4fa2

Accessing lazy2
In Constructor : Lazy
com.bethecoder.tutorials.spring3.basic.LazyBean@1e0f2f6



 
  


  
bl  br