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

Initialization Callback 

Spring Inversion of Control (IoC) also known as Dependency Injection (DI) is a process by which objects define their dependencies with collaborating objects. Spring provides a better alternative to using InitializingBean interface. The attribute init-method allows us to specify a no-argument method as an initialization callback method.

File Name  :  
/SpringCore001/conf/callback/init2.xml 

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


public class SimpleInitBean2 {

  private String simpleProp;

  public String getSimpleProp() {
    return simpleProp;
  }

  public void setSimpleProp(String simpleProp) {
    this.simpleProp = simpleProp;
  }

  public void init() {

    System.out.println("In custom init callback : " + simpleProp);
    
    simpleProp += "@callback"
      
    System.out.println("In custom init callback : " + simpleProp);
  }
  
  public String toString() {
    return "SimpleInitBean2[" + simpleProp + "]";
  }
  
}
   

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

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

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

public class InitializationCallback2 {

  /**
   @param args
   */
  public static void main(String[] args) {
    
    System.out.println("Initializing ApplicationContext");
    ApplicationContext factory = new ClassPathXmlApplicationContext("init2.xml");
    System.out.println("ApplicationContext Initialized");
    
    System.out.println("Accessing first bean");
    SimpleInitBean2 first = (SimpleInitBean2factory.getBean("first");
    System.out.println(first);

    System.out.println("Accessing second bean");
    SimpleInitBean2 second = (SimpleInitBean2factory.getBean("second");
    System.out.println(second);
  }

}
   

It gives the following output,
Initializing ApplicationContext
ApplicationContext Initialized

Accessing first bean
In custom init callback : FIRST
In custom init callback : FIRST@callback
SimpleInitBean2[FIRST@callback]

Accessing second bean
In custom init callback : SECOND
In custom init callback : SECOND@callback
SimpleInitBean2[SECOND@callback]



 
  


  
bl  br