Skip to main content

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

Mastering Java Logging: A Guide to Debug, Info, Warn, and Error Levels

Comprehensive Guide to Java Logging Levels: Trace, Debug, Info, Warn, Error, and Fatal Comprehensive Guide to Java Logging Levels: Trace, Debug, Info, Warn, Error, and Fatal Logging is an essential aspect of application development and maintenance. It helps developers track application behavior and troubleshoot issues effectively. Java provides various logging levels to categorize messages based on their severity and purpose. This article covers all major logging levels: Trace , Debug , Info , Warn , Error , and Fatal , along with how these levels impact log printing. 1. Trace The Trace level is the most detailed logging level. It is typically used for granular debugging, such as tracking every method call or step in a complex computation. Use this level sparingly, as it can generate a large volume of log data. 2. Debug The Debug level provides detailed information useful during dev...

Choosing Between Envoy and NGINX Ingress Controllers for Kubernetes

As Kubernetes has become the standard for deploying containerized applications, ingress controllers play a critical role in managing how external traffic is routed to services within the cluster. Envoy and NGINX are two of the most popular options for ingress controllers, and each has its strengths, weaknesses, and ideal use cases. In this blog, we’ll explore: How both ingress controllers work. A detailed comparison of their features. When to use Envoy vs. NGINX for ingress management. What is an Ingress Controller? An ingress controller is a specialized load balancer that: Manages incoming HTTP/HTTPS traffic. Routes traffic to appropriate services based on rules defined in Kubernetes ingress resources. Provides features like TLS termination, path-based routing, and host-based routing. How Envoy Ingress Controller Works Envoy , initially built by Lyft, is a high-performance, modern service proxy and ingress solution. Here's how it operates in Kubernetes: Ingress Resource : You d...

How to Identify High-Growth Stocks: Key Metrics and Analysis

Identifying high-growth stocks can significantly enhance your investment portfolio's performance. By analyzing key financial metrics, growth indicators, and market opportunities, you can pinpoint companies with the potential for exceptional returns. This blog outlines the critical factors to consider when selecting high-growth stocks. Key Metrics for High-Growth Stocks 1. Earnings Growth Consistent earnings growth is a hallmark of high-growth stocks. Look for companies with a double-digit EPS (Earnings Per Share) growth rate over several years, indicating strong profitability. 2. Revenue Growth Revenue growth shows the company’s ability to expand its market share or increase sales. Look for annual revenue growth rates above 15-20% . 3. Return on Equity (ROE) ROE measures how effectively a company uses shareholders' equity to generate profit. A high ROE (above 15-20% ) is ideal for high-growth companies. 4. Profit Margins Gross...