Saturday, August 10, 2013

Spring InitializingBean and DisposableBean Example

In Spring, If You want to perform specific actions on Bean Initialization or Destruction then Spring abstract Interface InitializingBean and DisposableBean are for You !

InitializingBean is abstract interface which has abstract method called afterPropertiesSet. If You have any bean which implements this interface then after all bean properties are set, this afterPropertiesSet method will be called.

DisposableBean is abstract Interface which has abstract method called destroy. If You have any bean which implements this interface then after bean is released by Spring container, this method will be called.

Spring InitializingBean and DisposableBean Example :

package com.anuj.spring.core.initializingandDesposable;

import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;

/**
 *
 * @author Anuj Patel
 */
public class Customer implements InitializingBean,DisposableBean{
    
    String customerId;

    public String getCustomerId() {
        return customerId;
    }

    public void setCustomerId(String customerId) {
        this.customerId = customerId;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("Init method after properties are set : "+ customerId);
    }

    @Override
    public void destroy() throws Exception {
        System.out.println("Destroy called !! Customer Clean Up");
    }

 @Override
 public String toString() {
  return "Customer [customerId=" + customerId + "]";
 } 
    
}

Spring Bean Configuration :


    
        
    


Get Customer Bean from Context :
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 *
 * @author Anuj Patel
 */
public class InitializingAndDisposableApp {

    public static void main(String[] args) {
        ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("spring_core_initializinganddisposable.xml");
        Customer customer = (Customer) context.getBean("customerBean");
        System.out.println(customer);
        
        context.close();
    }
}

Output :
log4j:WARN No appenders could be found for logger (org.springframework.core.env.StandardEnvironment).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
Init method after properties are set : 1
Customer [customerId=1]
Destroy called !! Customer Clean Up