Close

Spring - Receiving lifecycle callbacks by using 'initMethod' and 'destroyMethod' of @Bean annotation

[Last Updated: Mar 14, 2021]

Spring's @Bean annotation provides following optional elements to received lifecycle callbacks:

  1. initMethod: specifies the method name to received callback after bean initialization.
  2. destroyMethod: specified the method name to receive callback before bean destruction.

Example

package com.logicbig.example;

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

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

public class MyBean {
  private OtherBean otherBean;

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

  public void myPostConstruct() {
      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()");
  }


  public void cleanUp() {
      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(initMethod = "myPostConstruct", destroyMethod = "cleanUp")
  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@10b45b87
setOtherBean(): com.logicbig.example.OtherBean@2854b7f7
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

Using 'initMethod' and 'destroyMethod' of @Bean annotation. Select All Download
  • spring-lifecycle-callbacks-using-bean-annotation
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • MyBean.java

    See Also