Interface based method for Lifecycle events in Bean

February 16, 2018

We will see howe we can use interface to implement the lifecycle events of the bean. You can have two intrfaces. One is InitializingBean and has a method afterPropertiesSet. Other interface is DisposableBean which has the destroy . This method will be fired by Spring when you do not have rerefence to the bean and redy for garbage collection

package com.kayak;

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

public class Car implements InitializingBean,DisposableBean {

    Engine engine;
    private String name;
 
  
    public Car(String name) {
      this.name= name;
      System.out.println("Constructor method called");
    }
    

    public String getName() {
        return name;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("afterPropertiesSet method called");
    }

    @Override
    public void destroy() throws Exception {
            System.out.println("Object Disposed");
    }

}

You can write the followong main() to test this code

public static void main(String[] args) {
        
        ApplicationContext ctx = new  ClassPathXmlApplicationContext("bean.xml");
        Car car=(Car)ctx.getBean("car");
}

Output :

run:
Feb 16, 2018 1:31:11 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@3d646c37: startup date [Fri Feb 16 13:31:11 IST 2018]; root of context hierarchy
Feb 16, 2018 1:31:11 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [bean.xml]
Constructor method called
afterPropertiesSet method called
BUILD SUCCESSFUL (total time: 1 second)