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

Advanced Kafka Resilience: Dead-Letter Queues, Circuit Breakers, and Exactly-Once Delivery

Introduction In distributed systems, failures are inevitable—network partitions, broker crashes, or consumer lag can disrupt data flow. While retries help recover from transient issues, you need stronger guarantees for mission-critical systems. This guide covers three advanced Kafka resilience patterns: Dead-Letter Queues (DLQs) – Handle poison pills and unprocessable messages. Circuit Breakers – Prevent cascading failures when Kafka is unhealthy. Exactly-Once Delivery – Avoid duplicates in financial/transactional systems. Let's dive in! 1. Dead-Letter Queues (DLQs) in Kafka What is a DLQ? A dedicated Kafka topic where "failed" messages are sent after max retries (e.g., malformed payloads, unrecoverable errors). ...

Project Reactor Important Methods Cheat Sheet

🔹 1️⃣ subscribeOn – "Decides WHERE the Pipeline Starts" 📝 Definition: subscribeOn influences the thread where the data source (upstream) (e.g., data generation, API calls) runs . It affects the source and everything downstream (until a publishOn switches it). Flux<Integer> flux = Flux.range(1, 3) .doOnNext(i -> System.out.println("[Generating] " + i + " on " + Thread.currentThread().getName())) .subscribeOn(Schedulers.boundedElastic()) // Change starting thread .map(i -> { System.out.println("[Processing] " + i + " on " + Thread.currentThread().getName()); return i * 10; }); flux.blockLast(); Output: [Generating] 1 on boundedElastic-1 [Processing] 1 on boundedElastic-1 [Generating] 2 on boundedElastic-1 [Processing] 2 on boundedElastic-1 [Generating] 3 on boundedElastic-1 [Processing] 3 on boundedElastic-1 📢 Key Insight: ...

🔄 Kafka Producer Internals: send() Explained with Delivery Semantics and Transactions

Kafka Producer Internal Working Apache Kafka is known for its high-throughput, fault-tolerant message streaming system. At the heart of Kafka's data pipeline is the Producer —responsible for publishing data to Kafka topics. This blog dives deep into the internal workings of the Kafka Producer, especially what happens under the hood when send() is called. We'll also break down different delivery guarantees and transactional semantics with diagrams. 🧠 Table of Contents Kafka Producer Architecture Overview What Happens When send() is Called Delivery Semantics Kafka Transactions & Idempotence Error Handling and Retries Diagram: Kafka Producer Internals Conclusion 🏗️ Kafka Producer Architecture Overview Kafka Producer is composed of the following core components: Serializer : Converts key/value to bytes. Partitioner : Determines which partition a record should go to. Accumulator : Buffers the records in memory be...