Close

Spring - Receiving lifecycle callbacks by implementing InitializingBean and DisposableBean

[Last Updated: Mar 14, 2021]

The interface InitializingBean has one method afterPropertiesSet which is called by spring framework after it has set all bean properties.

The interface DisposableBean has one method destroy which is called by spring framework when JVM sends the shutdown signal.

Example

package com.logicbig.example;

public class OtherBean {
}
package com.logicbig.example;

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

public class MyBean implements InitializingBean, DisposableBean {
  private OtherBean otherBean;

  public MyBean() {
      System.out.println("MyBean constructor: " + this);
  }

  @Override
  public void afterPropertiesSet() {
      System.out.println("myPostConstruct()");
  }

  @Autowired
  public void setOtherBean(OtherBean otherBean) {
      System.out.println("setOtherBean(): " + otherBean);
      this.otherBean = otherBean;
  }

  public void doSomething() {
      System.out.println("doSomething()");
  }

  @Override
  public void destroy() {
      System.out.println("cleanUp method");
  }
}
package com.logicbig.example;

import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class LifeCycleExample {

  @Bean
  public MyBean myBean() {
      return new MyBean();
  }

  @Bean
  public OtherBean otherBean() {
      return new OtherBean();
  }

  public static void main(String[] args) {
      ConfigurableApplicationContext context =
              new AnnotationConfigApplicationContext(LifeCycleExample.class);

      context.registerShutdownHook();

      System.out.println("-- accessing bean --");
      MyBean bean = context.getBean(MyBean.class);
      bean.doSomething();

      System.out.println("-- finished --");
  }
}

Output

MyBean constructor: com.logicbig.example.MyBean@11a4dac4
setOtherBean(): com.logicbig.example.OtherBean@575532fe
myPostConstruct()
-- accessing bean --
doSomething()
-- finished --
cleanUp method

Example Project

Dependencies and Technologies Used:

  • spring-context 4.3.8.RELEASE: Spring Context.
  • JDK 1.8
  • Maven 3.6.3

Implementing InitializingBean and DisposableBean Select All Download
  • spring-lifecycle-callbacks-using-Initializing-disposable-bean
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • MyBean.java

    See Also