Search This Blog

Monday 23 April 2012

The InitializingBean and DisposableBean Interfaces

In our previous post we saw how the Spring container used custom initialization and destroy methods. An alternative way to achieve the same is to use the InitializingBean and DisposableBean Interfaces.
public class InitDestroyCar implements ICar, InitializingBean, DisposableBean {
    private Engine combustEngine;
    
    public InitDestroyCar() {
        System.out.println("Creating object");
    }

    public Engine getCombustEngine() {
        return combustEngine;
    }

    public void setCombustEngine(Engine combustEngine) {
        System.out.println("Setting the properties");
        this.combustEngine = combustEngine;
    }

    public void checkEngine() {
        System.out.println("Checking if engine is fine");
        // engine checkup code
    }

    public void cleanCar() {
        System.out.println("Cleaning the car after use");
        // engine clearance code
    }
    
    @Override
    public String describe() {
        return "Car in use " + this + ", engine is " + this.getCombustEngine();
    }

    @Override
    public void destroy() throws Exception {
        this.cleanCar();
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        this.checkEngine();        
    }
}
The InitializingBean interface exposes the afterPropertiesSet() method which is invoked by the Container when the Bean has been created and configured. The DisposableBean interface on the other hand exposes a destroy() method which will be invoked by the container when the bean is ready to be disposed of by the container. So I decided to check the engine in the afterPropertiesSet() method and clean the car in the destroy() method.
public static void main(String[] args) {
    XmlBeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("init-destroy-beans.xml"));
    InitDestroyCar car = (InitDestroyCar) beanFactory.getBean("car2");
    System.out.println(car.describe());
    beanFactory.destroyBean("car2",car);
}
The output of the method is:
Creating object
Setting the properties
Checking if engine is fine
Car in use com.car.InitDestroyCar@fec107, engine is Engine - com.car.Engine@132e13d and name Combusto
Cleaning the car after use

No comments:

Post a Comment