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

Initializing Bean 

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 InitializingBean interface which allows us to perform post processing tasks after bean initialization by Spring container.

InitializingBean.java  
package org.springframework.beans.factory;

public abstract interface InitializingBean
{
  public abstract void afterPropertiesSet() throws Exception;
}
File Name  :  
/SpringCore001/conf/callback/init.xml 

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

import org.springframework.beans.factory.InitializingBean;

public class SimpleInitBean implements InitializingBean {

  private String simpleProp;

  public String getSimpleProp() {
    return simpleProp;
  }

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

  @Override
  public void afterPropertiesSet() throws Exception {

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

File Name  :  
com/bethecoder/tutorials/spring3/tests/callbacks/InitializationCallback.java 
Author  :  Sudhakar KV
Email  :  kvenkatasudhakar@gmail.com
   
package com.bethecoder.tutorials.spring3.tests.callbacks;

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

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

public class InitializationCallback {

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

    System.out.println("Accessing second bean");
    SimpleInitBean second = (SimpleInitBeanfactory.getBean("second");
    System.out.println(second);
  }

}
   

It gives the following output,
Initializing ApplicationContext
ApplicationContext Initialized

Accessing first bean
In afterPropertiesSet callback : FIRST
In afterPropertiesSet callback : FIRST@callback
SimpleInitBean[FIRST@callback]

Accessing second bean
In afterPropertiesSet callback : SECOND
In afterPropertiesSet callback : SECOND@callback
SimpleInitBean[SECOND@callback]


                    Print

   



Books Recommendation

 
 
bl  br