Saturday, August 31, 2013

Init-method and Destroy-method Spring Bean example

If You want to perform specific action or handling upon bean Initialization and Bean destruction then Implementing InitializingBean and Disposable Bean is for You !!

But there is another approach also available if you don't want to implement those interfaces..You can add init-method and destroy-method into your spring bean configuration file at bean level.


You know what? You can also use annotation approch to achieve same. in that case you just need to annotate methods with @PostConstruct and @PreDestroy annotation in you bean class.

Spring Init-method and Destroy-method example :
package com.anuj.spring.core.initandDestroy;
package com.anuj.spring.core.initandDestroy;

/**
 *
 * @author Anuj Patel
 */
public class Customer{
    
    String customerId;

    public String getCustomerId() {
        return customerId;
    }

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

    public void init() throws Exception {
        System.out.println("Init method called. Values after properties set : "+ customerId);
    }

    public void clean() throws Exception {
        System.out.println("clean called !! Customer Clean Up");
    }    
}

Spring InitandDestroyApp:
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

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

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

Spring bean configuration File :


 
  
 


Output :
Init method called. Values after properties set : 1
com.anuj.spring.core.initandDestroy.Customer@1a44220
clean called !! Customer Clean Up

Author : Anuj Patel
Blog : http://goldenpackagebyanuj.blogspot.in/