Explore Courses
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Birla Institute of Management Technology Birla Institute of Management Technology Post Graduate Diploma in Management (BIMTECH)
  • 24 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Popular
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science & AI (Executive)
  • 12 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
University of MarylandIIIT BangalorePost Graduate Certificate in Data Science & AI (Executive)
  • 8-8.5 Months
upGradupGradData Science Bootcamp with AI
  • 6 months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
OP Jindal Global UniversityOP Jindal Global UniversityMaster of Design in User Experience Design
  • 12 Months
Popular
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Rushford, GenevaRushford Business SchoolDBA Doctorate in Technology (Computer Science)
  • 36 Months
IIIT BangaloreIIIT BangaloreCloud Computing and DevOps Program (Executive)
  • 8 Months
New
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Popular
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
Golden Gate University Golden Gate University Doctor of Business Administration in Digital Leadership
  • 36 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
Popular
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
Bestseller
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
IIIT BangaloreIIIT BangalorePost Graduate Certificate in Machine Learning & Deep Learning (Executive)
  • 8 Months
Bestseller
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in AI and Emerging Technologies (Blended Learning Program)
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
ESGCI, ParisESGCI, ParisDoctorate of Business Administration (DBA) from ESGCI, Paris
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration From Golden Gate University, San Francisco
  • 36 Months
Rushford Business SchoolRushford Business SchoolDoctor of Business Administration from Rushford Business School, Switzerland)
  • 36 Months
Edgewood CollegeEdgewood CollegeDoctorate of Business Administration from Edgewood College
  • 24 Months
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with Concentration in Generative AI
  • 36 Months
Golden Gate University Golden Gate University DBA in Digital Leadership from Golden Gate University, San Francisco
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Deakin Business School and Institute of Management Technology, GhaziabadDeakin Business School and IMT, GhaziabadMBA (Master of Business Administration)
  • 12 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science (Executive)
  • 12 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityO.P.Jindal Global University
  • 12 Months
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (AI/ML)
  • 36 Months
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDBA Specialisation in AI & ML
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
New
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGrad KnowledgeHutupGrad KnowledgeHutAzure Administrator Certification (AZ-104)
  • 24 Hours
KnowledgeHut upGradKnowledgeHut upGradAWS Cloud Practioner Essentials Certification
  • 1 Week
KnowledgeHut upGradKnowledgeHut upGradAzure Data Engineering Training (DP-203)
  • 1 Week
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
Loyola Institute of Business Administration (LIBA)Loyola Institute of Business Administration (LIBA)Executive PG Programme in Human Resource Management
  • 11 Months
Popular
Goa Institute of ManagementGoa Institute of ManagementExecutive PG Program in Healthcare Management
  • 11 Months
IMT GhaziabadIMT GhaziabadAdvanced General Management Program
  • 11 Months
Golden Gate UniversityGolden Gate UniversityProfessional Certificate in Global Business Management
  • 6-8 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
IU, GermanyIU, GermanyMaster of Business Administration (90 ECTS)
  • 18 Months
Bestseller
IU, GermanyIU, GermanyMaster in International Management (120 ECTS)
  • 24 Months
Popular
IU, GermanyIU, GermanyB.Sc. Computer Science (180 ECTS)
  • 36 Months
Clark UniversityClark UniversityMaster of Business Administration
  • 23 Months
New
Golden Gate UniversityGolden Gate UniversityMaster of Business Administration
  • 20 Months
Clark University, USClark University, USMS in Project Management
  • 20 Months
New
Edgewood CollegeEdgewood CollegeMaster of Business Administration
  • 23 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
KnowledgeHut upGradKnowledgeHut upGradBackend Development Bootcamp
  • Self-Paced
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 5 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
upGradupGradUI/UX Bootcamp
  • 3 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
upGradupGradDigital Marketing Accelerator Program
  • 05 Months

Spring Bean Life Cycle Explained [With Coding Example]

Updated on 12 December, 2024

22.34K+ views
17 min read

Think of the Spring bean life cycle like setting up and managing a library. First, books (beans) are ordered (created), then they’re sorted and placed in the right section (dependencies injected), and finally, when they’re no longer needed, they’re checked out or recycled (destroyed).

If you don't follow the right steps—ordering, sorting, or removing books properly—the library becomes disorganized and inefficient. Similarly, in Spring development, understanding the Spring bean life cycle helps you manage your application's components effectively. 

Mastering this process ensures that your application runs smoothly, avoiding errors and inefficiencies. This guide will walk you through the Spring bean life cycle, helping you build more reliable Spring applications and giving your career a valuable boost in the process. Dive in!

What is a Spring Bean Life Cycle? A Step-by-Step Breakdown With Examples

In Spring, beans are objects that are managed by the Spring IoC (Inversion of Control) container. The Spring container controls the complete life cycle of beans, from instantiation to destruction. 

Understanding the Spring bean life cycle is crucial for managing application components efficiently. Below is a detailed breakdown of the key stages in the Spring Bean life cycle.

Bean in Java Spring Explained

A Spring bean is simply a Java object that is created, configured, and managed by the Spring container. 

The Spring container handles the following key aspects of the bean life cycle:

  • Instantiating the bean
  • Injecting dependencies
  • Initializing the bean
  • Using the bean within the application
  • Destroying the bean when no longer needed

The Spring container manages all these stages, allowing developers to focus on building business logic rather than worrying about bean management.

Also Read: Spring vs Spring Boot: Difference Between Spring and Spring Boot

Spring Bean Life Cycle Explained

The Spring bean life cycle defines the series of stages a bean undergoes from its creation to its destruction within the Spring container. Understanding this life cycle is essential for managing Spring beans efficiently and ensuring that resources are properly allocated and released.

1. Bean Instantiation

In the first step of the Spring Bean life cycle, the Spring container creates an instance of the bean class. 

This process involves the following:

Role of Bean Definitions: Each bean in Java Spring container is defined in a configuration file (XML or Java Config) or through annotations like @Component. The bean definition specifies how the bean should be created and initialized.

Bean Creation: The Spring container uses the bean definition to instantiate the bean in Java Spring. This can happen when the application starts or when the bean is requested (in case of lazy loading).

Example:

In XML configuration:

<bean id="myBean" class="com.example.MyBean" />

In Java configuration:

@Configuration
public class AppConfig {
    @Bean
    public MyBean myBean() {
        return new MyBean();
    }
}

Also Read: Top Spring Boot Features for Java Developers

2. Dependency Injection

Once the bean is instantiated, the Spring container performs dependency injection to set the necessary properties or dependencies for the bean in Java Spring.

  • Constructor-based Injection: The Spring container passes dependencies through the constructor of the bean.
  • Setter-based Injection: The dependencies are set using setter methods.
  • @Autowired Annotation: This annotation helps Spring automatically inject dependencies into the bean in Java Spring.

Example:

In Constructor-based Injection:

public class MyBean {
    private SomeService someService;

    // Constructor-based injection
    public MyBean(SomeService someService) {
        this.someService = someService;
    }
}

In Setter-based Injection:

public class MyBean {
    private SomeService someService;

    // Setter-based injection
    @Autowired
    public void setSomeService(SomeService someService) {
        this.someService = someService;
    }
}

Also Read: Spring MVC Architecture in Java: Diagram, Advantages and Examples

3. Bean Initialization

After dependency injection, Spring invokes lifecycle hooks to initialize the bean. This is where you can perform custom initialization logic if needed.

  • @PostConstruct Annotation: This annotation is used to mark a method that should be called after the bean's properties are set.
  • InitializingBean Interface: You can implement the afterPropertiesSet() method to perform initialization logic.
  • Custom Initialization Method: You can specify a custom initialization method using the init-method attribute in XML or Java configuration.

Example:

Using @PostConstruct:

import javax.annotation.PostConstruct;

public class MyBean {
    
    @PostConstruct
    public void init() {
        System.out.println("Custom initialization logic executed!");
    }
}

Using InitializingBean Interface:

import org.springframework.beans.factory.InitializingBean;

public class MyBean implements InitializingBean {
    
    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("Initializing logic after properties set");
    }
}

Custom Initialization in Java Configuration:

@Configuration
public class AppConfig {

    @Bean(initMethod = "init")
    public MyBean myBean() {
        return new MyBean();
    }
}

Also Read: Top 10 Exciting Spring Boot Projects & Topics For Beginners

4. Bean Usage

Once the bean is initialized, it can be used within the application context. The bean in Java Spring is ready for interaction with other beans or components in the application.

  • Application Context: The Spring container (application context) holds references to all the beans and their dependencies.
  • Bean Interaction: Beans can interact with each other by calling methods on other beans. These interactions can be automatic due to dependency injection or manual.

Example:

public class MyBean {
    private SomeService someService;

    // Constructor-based dependency injection
    public MyBean(SomeService someService) {
        this.someService = someService;
    }

    public void performTask() {
        someService.execute();
    }
}

In this example, MyBean is using the SomeService bean to perform a task.

Also Read: Spring Boot Basic Annotations Everyone Should Know

5. Bean Destruction

When the Spring container is destroyed or when a bean is no longer needed, it goes through the destruction phase.

  • @PreDestroy Annotation: This annotation marks a method that should be called before the bean is destroyed.
  • DisposableBean Interface: You can implement the destroy() method to specify cleanup logic.
  • Custom Destruction Method: Similar to initialization, you can specify a custom destruction method using destroy-method in XML or Java configuration.

Example:

Using @PreDestroy:

import javax.annotation.PreDestroy;

public class MyBean {
    
    @PreDestroy
    public void cleanup() {
        System.out.println("Cleanup logic executed before destruction");
    }
}

Using DisposableBean Interface:

import org.springframework.beans.factory.DisposableBean;

public class MyBean implements DisposableBean {
    
    @Override
    public void destroy() throws Exception {
        System.out.println("Destroying bean and releasing resources");
    }
}

Custom Destruction in Java Configuration:

@Configuration
public class AppConfig {

    @Bean(destroyMethod = "cleanup")
    public MyBean myBean() {
        return new MyBean();
    }
}

Summary of Each Step in the Spring Bean Life Cycle:

  • Bean Instantiation: Spring creates the bean instance using the bean definition.
  • Dependency Injection: Spring injects dependencies into the bean through constructor or setter injection.
  • Bean Initialization: Initialization methods like @PostConstruct or InitializingBean are called to perform custom setup.
  • Bean Usage: The bean is used within the application, interacting with other beans.
  • Bean Destruction: Cleanup methods like @PreDestroy or DisposableBean are invoked before the bean is destroyed.

By following these steps and using the right annotations, you can effectively manage Spring bean life cycles. 

To master Spring and Java development, check out this free upGrad course on Core Java Basics.

Also Read: Top 18 Exciting Spring Projects Ideas & Topics For Beginners

Now, let's dive into the different methods for implementing the Spring bean lifecycle in your application.

How to Implement Spring Bean Life Cycle?

Managing the Spring bean lifecycle is crucial for efficient resource handling. Spring offers three approaches for custom init() and destroy() methods, ensuring proper initialization and clean shutdown.

Let’s explore the three ways to implement the Spring bean lifecycle with practical examples: using annotations, programmatically via interfaces, and XML configuration.

Using Annotations

The annotation-based approach is the most modern and convenient way to manage the lifecycle of Spring beans. With annotations such as @PostConstruct and @PreDestroy, Spring automatically invokes these methods when the container is initialized and destroyed.

Steps to Implement:

  • Step 1: Define the init() and destroy() methods in the HelloWorld bean class and annotate them with @PostConstruct and @PreDestroy respectively.
package beans;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

public class HelloWorld {

    @PostConstruct
    public void init() throws Exception {
        System.out.println("Bean HelloWorld has been instantiated and I'm the init() method.");
    }

    @PreDestroy
    public void destroy() throws Exception {
        System.out.println("Container has been closed and I'm the destroy() method.");
    }
}
  • Step 2: Configure the spring.xml to activate the annotations.
<beans>
    <!-- Enable annotation-based lifecycle management -->
    <bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor"/>

    <!-- Define the HelloWorld bean -->
    <bean class="beans.HelloWorld"/>
</beans>
  • Step 3: Create a driver class to load the Spring container and trigger the lifecycle methods.
package test;

import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import beans.HelloWorld;

public class Client {

    public static void main(String[] args) throws Exception {
        // Load Spring configuration and instantiate beans
        ConfigurableApplicationContext cap = new ClassPathXmlApplicationContext("resources/spring.xml");

        // Close the container, triggering the destroy() method
        cap.close();
    }
}

Output:

Bean HelloWorld has been instantiated and I'm the init() method.
Container has been closed and I'm the destroy() method.

Also Read: Spring Boot Annotations: Definition, Advantages & Types

Using Programmatic Approach

In the programmatic approach, the InitializingBean and DisposableBean interfaces are used to implement lifecycle methods. The afterPropertiesSet() method is invoked when the bean is instantiated, and the destroy() method is triggered when the container shuts down.

Steps to Implement:

  • Step 1: Implement InitializingBean and DisposableBean interfaces in the HelloWorld class and override their respective methods.
package beans;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.DisposableBean;

public class HelloWorld implements InitializingBean, DisposableBean {

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("Bean HelloWorld has been instantiated and I'm the init() method.");
    }

    @Override
    public void destroy() throws Exception {
        System.out.println("Container has been closed and I'm the destroy() method.");
    }
}
  • Step 2: Configure the Spring XML to define the bean.
<beans>
    <bean id="hw" class="beans.HelloWorld"/>
</beans>
  • Step 3: Create a driver class to load the Spring container and trigger the lifecycle methods.
package test;

import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import beans.HelloWorld;

public class Client {

    public static void main(String[] args) throws Exception {
        // Load Spring configuration and instantiate the bean
        ConfigurableApplicationContext cap = new ClassPathXmlApplicationContext("resources/spring.xml");

        // Close the container, triggering the destroy() method
        cap.close();
    }
}

Output:

Bean HelloWorld has been instantiated and I'm the init() method.
Container has been closed and I'm the destroy() method.

Using XML Configuration

The traditional XML configuration method allows you to explicitly define the custom init() and destroy() methods for a Spring bean in the configuration file. This approach remains popular for legacy applications.

Steps to Implement:

  • Step 1: Define the init() and destroy() methods inside the HelloWorld bean class.
package beans;

public class HelloWorld {

    // Initialization method
    public void init() throws Exception {
        System.out.println("Bean HelloWorld has been instantiated and I'm the init() method.");
    }

    // Destruction method
    public void destroy() throws Exception {
        System.out.println("Container has been closed and I'm the destroy() method.");
    }
}
  • Step 2: Register the init() and destroy() methods in the Spring XML configuration file spring.xml.
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" 
    "http://www.springframework.org/dtd/spring-beans-2.0.dtd">

<beans>
    <bean id="hw" class="beans.HelloWorld" 
          init-method="init" destroy-method="destroy"/>
</beans>
  • Step 3: Create a driver class to load the Spring container, instantiate the bean, and invoke the lifecycle methods upon container shutdown.
package test;

import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Client {

    public static void main(String[] args) throws Exception {
        // Load the Spring XML configuration and instantiate the bean
        ConfigurableApplicationContext cap = new ClassPathXmlApplicationContext("resources/spring.xml");

        // Close the container, triggering the destroy() method
        cap.close();
    }
}

Output:

Bean HelloWorld has been instantiated and I'm the init() method.
Container has been closed and I'm the destroy() method.

Each Spring bean lifecycle approach—annotations, programmatic interfaces, and XML configuration—offers unique benefits, with annotations being the most modern and convenient.

The choice of which method to use depends on your application’s needs, the complexity of your configurations, and your personal preferences.

Also Read: Spring Web Services: Features, Architecture, Installation & Project Steps

Now that you’ve covered the different ways to implement the Spring bean lifecycle, let’s explore the key annotations and interfaces that help manage and customize this process.

upGrad’s Exclusive Software and Tech Webinar for you –

SAAS Business – What is So Different?

 

What are the Key Annotations and Interfaces for Spring Bean Lifecycle Management?

Understanding Spring annotations and interfaces for managing bean lifecycles is key to building maintainable, efficient applications. These tools help customize bean initialization, destruction, and behavior.

Let's break down the key annotations and interfaces involved in Spring bean lifecycle management.

1. @PostConstruct: Overview and Practical Use Cases

The @PostConstruct annotation is used to mark a method that should be executed after the bean has been fully initialized and all dependencies have been injected, but before the bean is used in the application.

Common Use Cases:

  • Custom Initialization: Any post-injection initialization that doesn't require complex setup.
  • Setting up connections: E.g., initializing a connection pool, setting default values, or preparing resources that depend on bean properties.

Example:

@PostConstruct
public void init() {
    System.out.println("Bean HelloWorld initialized!");
}

This method will be called after all properties have been set by the container, ensuring that the bean is ready for use.

2. @PreDestroy: Ensuring Proper Resource Cleanup

The @PreDestroy annotation marks a method that should be executed just before the bean is destroyed. This is ideal for cleanup operations like releasing resources, closing connections, or performing other necessary shutdown tasks.

Common Use Cases:

  • Resource Cleanup: Closing file streams, database connections, or network connections.
  • Releasing Locks: Ensuring that any locks or threads are properly released.

Example:

@PreDestroy
public void cleanup() {
    System.out.println("Bean HelloWorld is being destroyed, cleaning up resources...");
}

This method will be invoked just before the bean is removed from the container, ensuring proper resource management.

Also Read: Spring Bean Scopes: Singleton & Prototype Scopes

3. InitializingBean and DisposableBean: Alternative Lifecycle Management Interfaces

These are two interfaces provided by Spring that you can implement in your bean classes for lifecycle management.

InitializingBean: The afterPropertiesSet() method is called after the bean's properties have been set, providing a programmatic alternative to @PostConstruct.

DisposableBean: The destroy() method is called just before the bean is destroyed, offering an alternative to @PreDestroy.

Common Use Cases:

  • Performing Custom Initialization: Using InitializingBean to execute initialization logic programmatically.
  • Resource Cleanup: Using DisposableBean to clean up resources.

Example:

public class HelloWorld implements InitializingBean, DisposableBean {
    @Override
    public void afterPropertiesSet() {
        System.out.println("Bean HelloWorld initialized programmatically!");
    }
    
    @Override
    public void destroy() {
        System.out.println("Bean HelloWorld is being destroyed, cleanup in progress...");
    }
}

This approach is more programmatic and provides additional flexibility when compared to annotations.

4. BeanPostProcessor: Customizing Bean Behavior During Initialization and Destruction Phases

The BeanPostProcessor interface allows developers to create custom logic to execute during both the initialization and destruction phases of the Spring bean lifecycle. You can use this interface to perform tasks such as modifying beans before or after initialization, adding logging, or even applying specific behaviors to beans that meet certain criteria.

Common Use Cases:

  • Custom Initialization Logic: Modifying beans right after they are initialized but before they are used.
  • Intercepting Bean Destruction: Customizing the destruction phase of beans.

Example:

public class CustomBeanPostProcessor implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("Before Initialization: " + beanName);
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("After Initialization: " + beanName);
        return bean;
    }
}

In this example, the postProcessBeforeInitialization and postProcessAfterInitialization methods are invoked at appropriate points during the lifecycle. This approach provides powerful flexibility to intervene at different stages of bean initialization and destruction.

Here is the summary of key annotations and interfaces:

  • @PostConstruct: Automatically runs initialization logic after dependency injection.
  • @PreDestroy: Ensures that necessary cleanup occurs before the bean is destroyed.
  • InitializingBean & DisposableBean: Interfaces offering a programmatic approach to handle bean initialization and destruction.
  • BeanPostProcessor: Enables deep customization of bean behavior during both the initialization and destruction phases.

Also Read: Top 8 Reasons Why Java Is So Popular and Widely Used in 2025

With a clear understanding of key annotations and interfaces, let’s now look at some of the common challenges developers face when managing the Spring bean lifecycle.

What are the Common Challenges in Managing Spring Bean Life Cycle?

Managing the Spring bean lifecycle can be challenging in larger applications, especially with resource management, proper configuration, and scalability.

Below are some common challenges and practical solutions that developers face when handling the Spring bean lifecycle:

1. Improper Configuration: Failing to Configure Lifecycle Hooks Correctly

Issue: Incorrect or missing configurations for lifecycle methods like @PostConstruct or @PreDestroy can cause unexpected behavior or resource leaks.

Example: Not specifying the init-method or destroy-method in XML configurations, or forgetting to annotate lifecycle methods with @PostConstruct and @PreDestroy.

Solution: Double-check configuration files (XML, annotations, or JavaConfig) to ensure all lifecycle hooks are correctly set. It's also a good practice to use only one method of lifecycle management—either annotations or interfaces, to avoid conflicts.

2. Overlapping Lifecycle Methods: Conflict Between Annotations and Interface Methods

Issue: Using both annotations (@PostConstruct@PreDestroy) and implementing lifecycle interfaces (InitializingBeanDisposableBean) in the same bean can lead to conflicts.

Example: A bean implementing InitializingBean's afterPropertiesSet() and also using the @PostConstruct annotation might cause confusion about which method should be executed.

Solution: Avoid using both annotations and interface methods in the same bean. Choose either annotations or interfaces for lifecycle management based on your project needs.

Also Read: 22 Best Java Project Ideas & Topics For Beginners With Source Code

3. Resource Cleanup Issues: Neglecting Destruction Logic for Beans Managing Heavy Resources

Issue: Failing to implement proper cleanup logic in beans managing heavy resources (e.g., database connections, file streams) can result in memory leaks or resource locking.

Example: Not using @PreDestroy or DisposableBean.destroy() for cleaning up database connections when the Spring context is closed.

Solution: Always implement resource cleanup methods in beans managing external resources. Utilize @PreDestroy or DisposableBean to ensure proper cleanup during bean destruction.

4. Scalability Constraints: Managing Multiple Beans in Complex Applications

Issue: Handling lifecycle management for multiple beans in large, complex applications can become cumbersome and hard to track.

Example: Managing dependencies and lifecycle for numerous beans, especially in large microservices or multi-module applications, can lead to misconfigured beans or unexpected lifecycle execution order.

Solution: Use Spring's @Scope and @Lazy annotations to control bean instantiation and lifecycle. Additionally, consider using the @BeanPostProcessor to centralize lifecycle management logic and reduce redundancy in large applications.

Addressing these challenges requires careful planning of lifecycle hooks, ensuring proper configuration, and leveraging Spring’s built-in lifecycle management tools for better control over bean creation and destruction.

Also Read: Top 10 Advantages of Java Programming To Setup Your Career

Now that you've explored some common challenges, let's dive into the best practices for effectively managing Spring beans and ensuring smooth application performance.

What are the Best Practices for Managing Spring Beans?

Managing Spring beans effectively is crucial for ensuring application performance, maintainability, and ease of debugging. Adopting the right strategies ensures that beans are properly initialized, used, and destroyed, minimizing potential issues in large-scale applications.

Below are some best practices for handling the Spring bean lifecycle.

1. Use Annotations for Declarative Lifecycle Management

Best Practice: Leverage annotations like @Component@PostConstruct@PreDestroy, etc., to manage Spring beans' lifecycle declaratively.

Reason: Annotations provide a more concise, readable, and maintainable way to configure bean lifecycle methods, as opposed to using XML or JavaConfig alone.

Example:

  • @Component for defining beans.
  • @PostConstruct to run custom initialization logic.
  • @PreDestroy to ensure proper cleanup.

2. Document and Test Lifecycle Configurations Thoroughly

Best Practice: Always document lifecycle-related configurations and thoroughly test them in different scenarios (e.g., bean initialization, destruction).

Reason: Clear documentation and tests reduce errors and misunderstandings, ensuring that beans perform as expected in various application contexts.

Example: Include lifecycle tests that ensure proper behavior during application startup and shutdown.

3. Optimize Resource-Heavy Beans with Destruction Methods

Best Practice: Implement custom destroy() methods in beans that handle resource-heavy tasks (e.g., database connections, file I/O) to release resources effectively.

Reason: Proper cleanup ensures that resources like file handles, database connections, and other external resources are released when the bean is no longer needed, preventing memory leaks and performance issues.

Example: Use @PreDestroy or implement DisposableBean's destroy() method to release resources.

4. Employ BeanPostProcessor for Centralized Lifecycle Control

Best Practice: Use the BeanPostProcessor interface to centralize lifecycle management logic for beans.

Reason: This allows customization of bean initialization and destruction across all beans, providing a unified approach to modifying or enriching beans at runtime.

Example: Customize bean initialization or destruction logic by implementing postProcessBeforeInitialization() and postProcessAfterInitialization() methods.

By following these best practices, you ensure a more efficient, manageable, and scalable Spring application with well-controlled and predictable bean lifecycle behavior.

Ready to master JavaScript and improve your knowledge of Java Spring? Start learning with this free JavaScript basics course today!

Also Read: Careers in Java: How to Make a Successful Career in Java in 2025

To further enhance your expertise in the Spring Framework, consider exploring how upGrad's specialized programs can help you take your skills to the next level.

How Can upGrad Help You Master the Spring Framework?

Want to master the Spring Framework and boost your backend development skills? upGrad offers hands-on projects, mentorship, and expert guidance to help you succeed in Java backend development. 

Here's a quick look at some of the relevant courses offered:

Course Title

Description

Java Object-oriented Programming Master the fundamentals of OOP and learn key concepts like classes, inheritance, and polymorphism.
Master of Design in User Experience Gain expertise in creating intuitive, user-centered designs for digital products.
Best Full Stack Developer Bootcamp  Essential skills in both front-end and back-end development.
Learn Basic Python Free Course Coding exercises on lists, strings, and data structures like tuples, sets, and dictionaries.

You can also join upGrad’s offline centers for hands-on training in Java development. Learn from industry experts, gain real-world experience, and access free career counseling to find the perfect machine learning course. 

Discover our software development courses designed to enhance your skills and accelerate your career growth in the tech industry.

Frequently Asked Questions (FAQs)

1. What is the difference between singleton and prototype bean scopes in Spring?

Singleton beans are created once and shared across the Spring container, while prototype beans are created each time they are requested. The prototype scope is useful for beans that should have different states per request.

2. Can you use both @PostConstruct and InitializingBean in the same bean?

Yes, both can be used, but it is generally not recommended as they serve similar purposes. Using both could lead to redundant initialization steps and make the code less maintainable.

3. How does Spring manage beans in different application contexts (root vs. child contexts)?

The root context holds common beans, and child contexts inherit beans from the root unless explicitly overridden. Each context manages its beans independently, ensuring separation of concerns.

4. What is the role of the BeanFactoryPostProcessor and BeanPostProcessor in Spring's bean lifecycle?

BeanFactoryPostProcessor modifies the BeanFactory before beans are instantiated, while BeanPostProcessor provides hooks for modifying beans after they are instantiated. Both are used for advanced bean configuration and customization.

5. Can you customize the Spring Bean destruction lifecycle after the container is closed?

Yes, Spring allows the use of @PreDestroy or DisposableBean to implement custom cleanup logic before the container shuts down. This ensures resources are freed up properly before the container is closed.

6. What happens if a bean fails during the initialization phase?

If a bean fails to initialize, Spring throws a BeanInitializationException, which prevents the application context from being fully loaded. This ensures that no invalid or partially initialized beans are used during the application's runtime.

7. What is the order of execution for lifecycle annotations (@PostConstruct, @PreDestroy) in Spring?

The @PostConstruct annotation is executed immediately after the bean's construction, while @PreDestroy is called before the container shuts down. This ensures proper initialization and cleanup of resources.

8. How does Spring handle circular dependencies in bean initialization?

Spring resolves circular dependencies using proxies for beans with setter-based injection. However, if the dependencies are constructor-based, Spring will throw an exception unless @Lazy is used to break the cycle.

9. Can a bean be initialized asynchronously in Spring?

Yes, you can initialize a bean asynchronously using the @Async annotation or by executing the initialization logic in a separate thread. This can help improve the application's startup time for non-blocking tasks.

10. What happens if a @PreDestroy method throws an exception?

If a @PreDestroy method throws an exception, Spring logs it but continues destroying other beans. This ensures that the container can still shut down, but the failure to destroy one bean won't impact others.

11. How do Spring profiles affect the lifecycle of beans?

Spring profiles control the activation of beans based on the environment. Beans are instantiated only when their corresponding profile is active, which can impact their lifecycle events accordingly.

RELATED PROGRAMS