Understanding the Lifecycle of a Spring Bean: Initialization and Destruction Explained


Spring Framework is renowned for its robust management of application components. One of the key aspects that make Spring so powerful is its comprehensive bean lifecycle management. In this blog, we'll explore the complete lifecycle of a Spring bean, including initialization and destruction methods. We'll delve into the sequence in which these methods are called, using various interfaces, annotations, and custom methods to illustrate the process. 


Table of Contents

  1. Introduction to Spring Bean Lifecycle
  2. Spring Configuration and Bean Definition
  3. Bean Initialization Sequence
  4. Bean Destruction Sequence
  5. Complete Example with Output
  6. Conclusion

Introduction to Spring Bean Lifecycle

In Spring, a bean's lifecycle comprises various phases from instantiation, property population, and initialization to destruction. Understanding this lifecycle is crucial for developers to ensure proper resource management and application behavior.


Spring Configuration and Bean Definition

Before diving into the lifecycle methods, let's define our Spring configuration and the bean class.

XML Configuration (applicationContext.xml)


<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="myBean" class="com.example.MyBean" init-method="customInit" destroy-method="customDestroy"/>
    <bean class="com.example.CustomBeanPostProcessor"/>
</beans>

Java Configuration (Alternative to XML)

@Configuration
public class AppConfig {
    
    @Bean(initMethod = "customInit", destroyMethod = "customDestroy")
    public MyBean myBean() {
        return new MyBean();
    }
    
    @Bean
    public CustomBeanPostProcessor customBeanPostProcessor() {
        return new CustomBeanPostProcessor();
    }
}

Bean Initialization Sequence

During the initialization phase, Spring calls several methods in a specific order:

Bean Class (MyBean.java)



public class MyBean implements BeanNameAware, BeanFactoryAware, ApplicationContextAware, InitializingBean, DisposableBean {
    
    @Override
    public void setBeanName(String name) {
        System.out.println("BeanNameAware: setBeanName() called. Bean name is: " + name);
    }
    
    @Override
    public void setBeanFactory(BeanFactory beanFactory) {
        System.out.println("BeanFactoryAware: setBeanFactory() called.");
    }
    
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        System.out.println("ApplicationContextAware: setApplicationContext() called.");
    }

    @PostConstruct
    public void init() {
        System.out.println("@PostConstruct: init() method called.");
    }
    
    @Override
    public void afterPropertiesSet() {
        System.out.println("InitializingBean: afterPropertiesSet() method called.");
    }
    
    public void customInit() {
        System.out.println("Custom init-method: customInit() method called.");
    }

    @PreDestroy
    public void preDestroy() {
        System.out.println("@PreDestroy: preDestroy() method called.");
    }
    
    @Override
    public void destroy() {
        System.out.println("DisposableBean: destroy() method called.");
    }
    
    public void customDestroy() {
        System.out.println("Custom destroy-method: customDestroy() method called.");
    }
}

Bean Post Processor (CustomBeanPostProcessor.java)

public class CustomBeanPostProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) {
        System.out.println("BeanPostProcessor: postProcessBeforeInitialization() called for " + beanName);
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) {
        System.out.println("BeanPostProcessor: postProcessAfterInitialization() called for " + beanName);
        return bean;
    }
}

Main Application (MainApp.java)


public class MainApp {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        MyBean myBean = (MyBean) context.getBean("myBean");
        ((ClassPathXmlApplicationContext) context).close();
    }
}

Complete Example with Output

Running the MainApp class, you'll observe the following sequence of method calls, demonstrating the initialization and destruction order:


BeanNameAware: setBeanName() called. Bean name is: myBean 

BeanFactoryAware: setBeanFactory() called.

ApplicationContextAware: setApplicationContext() called. 

BeanPostProcessor: postProcessBeforeInitialization() called for myBean

@PostConstruct: init() method called.

InitializingBean: afterPropertiesSet() method called.

Custom init-method: customInit() method called. 

BeanPostProcessor: postProcessAfterInitialization() called for myBean

@PreDestroy: preDestroy() method called. 

DisposableBean: destroy() method called.

Custom destroy-method: customDestroy() method called.

Explanation of Output

  1. Aware Interfaces: Methods from BeanNameAware, BeanFactoryAware, and ApplicationContextAware are called first.
  2. BeanPostProcessor (Before Initialization): postProcessBeforeInitialization method is invoked.
  3. @PostConstruct: The method annotated with @PostConstruct is called.
  4. InitializingBean: The afterPropertiesSet() method is called.
  5. Custom Init Method: The custom initialization method specified in the configuration is called.
  6. BeanPostProcessor (After Initialization): postProcessAfterInitialization method is invoked.
  7. @PreDestroy: The method annotated with @PreDestroy is called during the destruction phase.
  8. DisposableBean: The destroy() method is called.
  9. Custom Destroy Method: The custom destroy method specified in the configuration is called.












Comments

Popular posts from this blog

12 Must-Know LeetCode+ Links for Coding Excellence

Stay Updated As Software Engineer

Getting Master in Hibernate and JPA