Show List

Spring Bean lifecycle

The lifecycle of a Spring bean refers to the various stages a bean goes through from its creation to its destruction. The lifecycle of a bean is managed by the Spring framework, and it consists of the following phases:

  1. Instantiation: Spring creates an instance of the bean using a constructor or a factory method.

  2. Dependency Injection: Spring injects any dependencies the bean may have, either through constructor arguments or setter methods.

  3. Post-Processing: If any bean post-processors are registered, they will be applied to the bean to allow for any additional configuration.

  4. Initialization: If the bean implements the InitializingBean interface, the afterPropertiesSet() method will be called, allowing for any additional initialization. If a @PostConstruct annotated method is present, it will also be called.

  5. Ready for Use: The bean is now fully initialized and ready for use by the application.

  6. Destruction: When the application context is closed, or when the bean is no longer required, the DisposableBean interface's destroy() method will be called, allowing for any necessary cleanup. If a @PreDestroy annotated method is present, it will also be called.

Note: The order of these phases can be influenced by various bean configuration settings and custom BeanPostProcessors.


Here's an example of a Spring bean that implements the InitializingBean interface and has a @PostConstruct annotated method:
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.InitializingBean;

public class ExampleBean implements InitializingBean {
   private String message;

   public ExampleBean(String message) {
      this.message = message;
   }

   @PostConstruct
   public void init() {
      System.out.println("@PostConstruct method called");
   }

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

   public String getMessage() {
      return message;
   }
}
And here's an example of a Spring bean that implements the DisposableBean interface and has a @PreDestroy annotated method:
import javax.annotation.PreDestroy;
import org.springframework.beans.factory.DisposableBean;

public class ExampleBean implements DisposableBean {
   private String message;

   public ExampleBean(String message) {
      this.message = message;
   }

   @PreDestroy
   public void cleanup() {
      System.out.println("@PreDestroy method called");
   }

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

   public String getMessage() {
      return message;
   }
}

    Leave a Comment


  • captcha text