Spring Boot Tutorial

Spring Boot - Software Setup and Configuration (STS/Eclipse/IntelliJ)

Prerequisite (Spring Core Concepts)

Spring Boot Core

Spring Boot with REST API

Spring Boot with Database and Data JPA

Spring Boot with Kafka

Spring Boot with AOP

Bean life cycle in Java Spring

In the Spring Framework, the lifecycle of a bean refers to the series of steps or events that a bean goes through from its instantiation until it is destroyed. Understanding the bean lifecycle is essential when working with Spring-based applications because it allows developers to tap into and customize various lifecycle events.

Here's an overview of the bean lifecycle in Spring:

  1. Instantiation: The very first step in the lifecycle of a bean. The Spring container creates an instance of the bean.

  2. Populate Properties: After instantiation, the Spring container injects the bean's properties using the dependency injection (DI) mechanism.

  3. Set Bean Name: If the bean implements BeanNameAware, the setBeanName method is called with the bean ID.

  4. Set Bean Factory: If the bean implements BeanFactoryAware, the setBeanFactory method is called, providing the bean with the instance of the bean factory that created it.

  5. Pre-initialization - Bean Post Processors: Before a bean's initialization method is invoked, all BeanPostProcessors' postProcessBeforeInitialization methods will be called.

  6. AfterPropertiesSet and Custom Init Method:

    • If the bean implements InitializingBean, the afterPropertiesSet method is invoked.
    • If a custom initialization method is specified (using the init-method attribute in XML or @Bean(initMethod = "methodName") in JavaConfig), that method is called.
  7. Post-initialization - Bean Post Processors: After a bean's initialization method is invoked, all BeanPostProcessors' postProcessAfterInitialization methods will be called.

  8. Bean is Ready to Use: At this point, the bean is fully constructed, initialized, and ready for use. It can now be retrieved from the container and used in the application.

  9. DisposableBean and Custom Destroy Method:

    • If your bean is a singleton (default scope) and the container is closed (typically in a web application during shutdown or in a standalone application when explicitly closing the ApplicationContext), the bean goes through a destruction phase.
    • If the bean implements DisposableBean, the destroy method is invoked.
    • If a custom destroy method is specified (using the destroy-method attribute in XML or @Bean(destroyMethod = "methodName") in JavaConfig), that method is called.
  10. Bean is Destroyed: The bean is no longer available once it's destroyed.

To hook into the bean lifecycle, you can implement the various Aware interfaces (like BeanNameAware, BeanFactoryAware, etc.), use InitializingBean and DisposableBean, or specify custom init and destroy methods. Additionally, you can use @PostConstruct and @PreDestroy annotations from the JSR-250 specification to define methods that should be executed after bean construction and just before bean destruction, respectively.

Furthermore, BeanPostProcessor can be implemented to perform operations before and after the bean initialization, giving developers a powerful mechanism to control the bean lifecycle and add custom behaviors during bean initialization.

  1. Methods in Spring Bean Life Cycle:

    • Description: The Spring Bean life cycle consists of various methods that are executed during the creation, initialization, and destruction of a bean. Key methods include afterPropertiesSet(), init-method, destroy(), and destroy-method.
    • Code Example:
      public class MyBean implements InitializingBean, DisposableBean {
      
          // Initialization method
          @Override
          public void afterPropertiesSet() throws Exception {
              // Initialization logic
          }
      
          // Destruction method
          @Override
          public void destroy() throws Exception {
              // Cleanup logic
          }
      }
      
  2. Callback Methods in Spring Bean Life Cycle:

    • Description: Callback methods such as afterPropertiesSet() and destroy() provide hooks for custom initialization and destruction logic. Additionally, custom methods annotated with @PostConstruct and @PreDestroy serve as callback points.
    • Code Example:
      public class MyBean {
      
          // Initialization callback
          @PostConstruct
          public void customInit() {
              // Custom initialization logic
          }
      
          // Destruction callback
          @PreDestroy
          public void customDestroy() {
              // Custom destruction logic
          }
      }
      
  3. Configuring Bean Life Cycle in Spring XML:

    • Description: In Spring XML configuration, you can define initialization and destruction methods using the init-method and destroy-method attributes in the bean definition.
    • Code Example:
      <bean id="myBean" class="com.example.MyBean" init-method="customInit" destroy-method="customDestroy"/>
      
  4. BeanPostProcessor in the Spring Bean Life Cycle:

    • Description: BeanPostProcessor is an interface that allows customization of bean instantiation and configuration. It provides hooks before and after the initialization of beans.
    • Code Example:
      public class MyBeanPostProcessor implements BeanPostProcessor {
      
          @Override
          public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
              // Custom logic before initialization
              return bean;
          }
      
          @Override
          public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
              // Custom logic after initialization
              return bean;
          }
      }
      
  5. Working with ApplicationContextAware in Spring:

    • Description: Implementing ApplicationContextAware allows a bean to be aware of the application context. This enables access to the context and its resources during the bean life cycle.
    • Code Example:
      public class MyBean implements ApplicationContextAware {
      
          private ApplicationContext applicationContext;
      
          @Override
          public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
              this.applicationContext = applicationContext;
          }
      }
      
  6. Customizing Bean Life Cycle with BeanFactoryPostProcessor:

    • Description: BeanFactoryPostProcessor allows custom modification of the bean factory configuration before bean instantiation. It provides the ability to manipulate bean definitions.
    • Code Example:
      public class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
      
          @Override
          public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
              // Custom logic to modify bean factory configuration
          }
      }
      
  7. Using SmartLifecycle Interface in Spring for Custom Life Cycle Management:

    • Description: SmartLifecycle interface provides fine-grained control over the bean life cycle. It allows beans to manage their startup and shutdown phases based on specific conditions.
    • Code Example:
      public class MySmartLifecycleBean implements SmartLifecycle {
      
          @Override
          public void start() {
              // Custom logic for starting the bean
          }
      
          @Override
          public void stop() {
              // Custom logic for stopping the bean
          }
      
          @Override
          public boolean isRunning() {
              // Custom logic to determine if the bean is currently running
              return false;
          }
      }