Spring Boot Lifecycle Hooks

A brief intro into Spring Lifecycle hooks

In this article we will talking about Spring Boot life cycle hooks and where we would use them.

We will covering below topics,

  1. What is a Bean in Spring Boot ?

    Its an object that is created and managed by Spring IOC. Basically any object managed by ApplicationContext class of Spring is called a Bean.

  2. What is Bean Life Cycle ?

    The spring Bean life cycle is as follows,

    Spring IOC container started—> Bean Initialized —> Dependency injected —> custom init method —> custom utility methods —> destroy method.

  3. What are life cycle hooks ?

    Life cycle hooks are functions that can be run before and after any of the above mentioned bean life cycle steps.

    To understand Spring boot life cycle hooks better, lets divide the spring bean lifecycle into below phases,

    Bean Creation Phase

    1. Instantiation Phase

      This phase happens just after Bean initialized step

    2. Populating Properties Phase

      This phase happens just before Dependency injected step

    3. Pre-Initialization Phase

      This phase is done after Dependecy injected step. Here postProcessBeforeInitialization methods gets called. Right after this @PostContruct methods gets called.

    4. AfterPropertiesSet Phase

      This phase happens after Dependecy Injected step but right before Pre-Initialization step.

    5. Custom Initialization Phase

      This phase basically happens during the custom init method life cycle. Here the methods defined in the initMethod defined within@Bean is triggered.

    6. Post-Initialization Phase

      After Custom Initialization phase, this phase is triggered. Here postProcessAfterInitialization method gets called.

    Bean Destruction Phase:

    Below phase starts getting executed , when a spring bean is been deleted by ApplicationContext.

    1. Pre-Destroy Phase

      Here Spring triggers @PreDestroy method.

    2. Destroy Phase

      Here @Destroy method of DisposableBean is called.

    3. Custom Destruction Phase

      Here method defined with destroyMethod under @Bean annotation is called.

    Now lets look into some of the life cycle hooks that Spring Boot provides.

Lifecycle Hooks

  1. Using interfaces

    We can implement lifecycle hooks using interfaces. To implement lifecycle hooks using interfaces we need to implement InitializingBean interface.

    Then any logic written within method afterPropertiesSet() gets implemented.

    Example:

    @Component
    class testBean implements InitializingBean {
    
      @Override
      public void afterPropertiesSet() {
        // Custom Logic
      }
    
    }
    
  2. Using JST-250 annotations

    This is basically @PreConstruct and @PostDestroy annotation. We can use these method during initialization and destroy phase of Bean to implement any logic

    @Component
    class testBean {
    
      @PostConstruct
      public void postConstruct() {
        //...
      }
    
      @PreDestroy
      public void preDestroy() {
        //...
      }
    
    }
    
  3. Using @Bean annotations

    We can also call methods during bean creation and bean destruction within @Bean annotation.

    @Configuration
    class testBean {
    
      @Bean(initMethod = "onInitialize", destroyMethod = "onDestroy")
      public NewBean getNewBean() {
        return new NewBean();
      }
    
    }
    
  4. Using BeanPostProcessor

    We can also implement BeanPostProcessor to trigger custom methods during and after bean creation. But this won’t be bean specific. For each and every bean in the application, implemented methods will be called.

    class TestBeanPostProcessor implements BeanPostProcessor {
    
      @Override
      public Object postProcessBeforeInitialization(Object bean, String beanName)
        throws BeansException {
        // test logic
        return bean;
      }
    
      @Override
      public Object postProcessAfterInitialization(Object bean, String beanName)
        throws BeansException {
        // test logic
        return bean;
      }
    
    }
    
  5. Using Aware Interfaces

    We can use Aware interfaces to hook to lifecycle of Bean.

    @Component
    class TestBean BeanNameAware, ApplicationContextAware {
    
      @Override
      public void setBeanName(String name) {
        // test logic
      }
    
      @Override
      public void setApplicationContext(ApplicationContext applicationContext)
        throws BeansException {
        // test logic
      }
    
    }
    

These are the different ways in which we can implement life cycle hooks in Spring Boot.

Some of real world use-cases of Spring Boot life cycle hooks are as follows,

  1. For logging purposes, wherein we might need to acquire bean names.
  2. If we suppose are using a bean that connects to a database and we need to to destroy the connection when the bean is destroyed, then in tha case, @PreDestroy method can be used.

For more articles on Java please check here.