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

Learning How to Map One-to-Many Relationships in JPA Spring Boot with PostgreSQL

  Introduction In this blog post, we explore how to effectively map one-to-many relationships using Spring Boot and PostgreSQL. This relationship type is common in database design, where one entity (e.g., a post) can have multiple related entities (e.g., comments). We'll dive into the implementation details with code snippets and provide insights into best practices. Understanding One-to-Many Relationships A one-to-many relationship signifies that one entity instance can be associated with multiple instances of another entity. In our case: Post Entity : Represents a blog post with fields such as id , title , content , and a collection of comments . Comment Entity : Represents comments on posts, including fields like id , content , and a reference to the post it belongs to. Mapping with Spring Boot and PostgreSQL Let's examine how we define and manage this relationship in our Spring Boot application: Post Entity  @Entity @Getter @Setter @Builder @AllArgsConstructor @NoArgsCons

Tree Based Common problems and patterns

  Find the height of the tree. public class BinaryTreeHeight { public static int heightOfBinaryTree (TreeNode root) { if (root == null ) { return - 1 ; // Height of an empty tree is -1 } int leftHeight = heightOfBinaryTree(root.left); int rightHeight = heightOfBinaryTree(root.right); // Height of the tree is the maximum of left and right subtree heights plus 1 for the root return Math.max(leftHeight, rightHeight) + 1 ; } Find the Level of the Node. private static int findLevel (TreeNode root, TreeNode node, int level) { if (root == null ) { return - 1 ; // Node not found, return -1 } if (root == node) { return level; // Node found, return current level } // Check left subtree int leftLevel = findLevel(root.left, node, level + 1 ); if (leftLevel != - 1 ) { return leftLevel; // Node found in t

Stay Updated As Software Engineer

Are you a software engineer looking to stay updated and grow in your field? We've got you covered with over 50 valuable resources to keep you on the cutting edge of technology. From newsletters to books, we've curated a diverse list just for you.   Newsletters:   Pragmatic Engineer: Link   TLDR: Link   Level-up software engineering: Link   Coding challenges: Link   Engineers Codex: Link   Techlead Mentor: Link   Saiyan Growth letter: Link   Wes Kao: Link   Addy Osmani: Link   And many more (see link below)   Books:   Engineering:   A Philosophy of Software Design Link   Clean Code Link   Communication & Soft Skills:   Smart Brevity Link   Connect: Building Exceptional Relationships Link   Crucial Conversations Link   Engineers Survival Guide Link   Leadership:   The Manager's Path Link   Staff Engineer: Leadership Beyond the Management Track Link   The Coaching Habit: Say Less, Ask More Link   While we can't list all 50+ resources here, this is a fantastic sta