Table of contents
1.
Why Understand the Spring Bean Life Cycle?
2.
Ways to Implement the Life Cycle of a Bean
2.1.
1. By XML Configuration
2.1.1.
Code Example:
2.1.2.
Advantages:
2.2.
2. By Programmatic Approach
2.2.1.
Code Example:
2.2.2.
Advantages:
2.3.
3. Using Annotations
2.3.1.
Code Example:
2.3.2.
Advantages:
3.
Stages of Spring Bean Life Cycle 
4.
Benefits of Exploring the Spring Bean Life Cycle
5.
​​Best Practices 
6.
Frequently Asked Questions
6.1.
When Does the Spring Bean Life Cycle Begin?
6.2.
How does managing the bean life cycle improve application performance?
6.3.
Can we mix different life cycle management methods in the same application?
6.4.
Are annotations always the best choice for life cycle management?
7.
Conclusion
Last Updated: Jul 11, 2024
Medium

Spring Bean Life Cycle

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

In the Spring framework, a fundamental concept for Java developers is the bean life cycle. This life cycle encompasses several stages, starting with the creation of a bean, followed by its initialization, use during the application's runtime, and finally, its destruction. Managed by the Spring container, this process offers developers the opportunity to inject custom behavior at different phases. 

spring bean life cycle

Understanding and effectively managing the bean life cycle is pivotal for creating efficient, robust, and maintainable Spring applications. Let's delve into the ways this life cycle can be implemented and managed within the Spring framework.

The spring bean life cycle is shown in the diagram below:

Life Cycle of a Bean

Why Understand the Spring Bean Life Cycle?

Understanding the Spring Bean life cycle is crucial for developers working with the Spring Framework as it provides insights into how Spring manages and initializes beans. Knowledge of the bean life cycle enables developers to customize bean initialization, destruction, and behavior, allowing for more efficient resource management, dependency injection, and integration of third-party libraries within Spring applications.

Ways to Implement the Life Cycle of a Bean

The life cycle of a bean in Spring can be implemented using initialization and destruction callbacks. Developers can define methods annotated with @PostConstruct and @PreDestroy for custom initialization and cleanup tasks, ensuring proper initialization and disposal of beans managed by the Spring container.

1. By XML Configuration

In this approach, the bean's life cycle methods are defined in an XML configuration file. This method involves specifying init-method and destroy-method attributes in the bean definition. The Spring container will call these methods at the appropriate life cycle stages.

Code Example:

XML Configuration (beans.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="init" destroy-method="cleanup">
        <!-- Bean properties -->
    </bean>
</beans>


Java Class (MyBean.java):

package com.example;

public class MyBean {
    public void init() {
        System.out.println("MyBean is initialized via XML.");
    }

    public void cleanup() {
        System.out.println("MyBean is destroyed via XML.");
    }
}


Advantages:

  • Clear separation of configuration from Java code.
     
  • Suitable for projects where XML-based configuration is preferred or legacy projects.

2. By Programmatic Approach

Explanation:

This approach uses the InitializingBean and DisposableBean interfaces provided by Spring. Implementing these interfaces allows defining afterPropertiesSet() and destroy() methods, respectively, providing explicit control over bean initialization and destruction.

Code Example:


Java Class Implementation (MyBean.java):

package com.example;

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

public class MyBean implements InitializingBean, DisposableBean {

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("MyBean is initialized via InitializingBean.");
    }

    @Override
    public void destroy() throws Exception {
        System.out.println("MyBean is destroyed via DisposableBean.");
    }
}

Advantages:

  • Direct control over the initialization and destruction process.
  • More explicit and programmatic, which can be preferable in Java-configured applications.

3. Using Annotations

Explanation:

Annotation-based configuration uses @PostConstruct and @PreDestroy annotations. These annotations are used to mark methods that should be executed after the bean is initialized and before it is destroyed, respectively. This approach aligns with modern Spring practices.

Code Example:

Java Class with Annotations (MyBean.java):

package com.example;

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

public class MyBean {
    @PostConstruct
    public void init() {
        System.out.println("MyBean is initialized via @PostConstruct.");
    }

    @PreDestroy
    public void cleanup() {
        System.out.println("MyBean is destroyed via @PreDestroy.");
    }
}

Advantages:

  • Simplicity and minimal boilerplate.
  • Enhances readability and maintainability of the code.

Also Read, spring mvc vs spring boot

Stages of Spring Bean Life Cycle 

Stages of Spring Bean Life Cycle:

  1. Instantiation: Spring container creates an instance of the bean using its constructor.
  2. Population of Properties: Spring injects dependencies and sets properties of the bean.
  3. Aware Interfaces: Spring invokes any callback methods implemented by the bean such as InitializingBean's afterPropertiesSet() or BeanNameAware's setBeanName().
  4. Custom Init Method: If configured, Spring calls custom initialization methods annotated with @PostConstruct or defined in XML.
  5. Bean Ready for Use: The bean is now fully initialized and ready for use by other beans or components.
  6. Bean Destruction: When the application context is shut down or the bean is no longer needed, Spring calls any destruction callbacks such as DisposableBean's destroy() method or methods annotated with @PreDestroy.

Benefits of Exploring the Spring Bean Life Cycle

Benefits of Exploring the Spring Bean Life Cycle:

  • Customization: Understanding the life cycle allows for custom initialization and destruction logic tailored to specific requirements.
  • Resource Management: Properly managing resources ensures efficient utilization and prevents memory leaks.
  • Debugging: Knowledge of the life cycle aids in debugging and troubleshooting issues related to bean initialization and destruction.
  • Integration: Integrating third-party libraries and frameworks becomes smoother with insight into how Spring manages bean life cycles.

​​Best Practices 

  • Consistent Naming: Follow consistent naming conventions for initialization and destruction methods to maintain clarity and readability.
  • Use Annotations: Prefer annotations like @PostConstruct and @PreDestroy over interface implementations for defining custom life cycle methods.
  • Avoid Heavy Processing: Minimize heavy processing in initialization methods to reduce application startup time.
  • Resource Cleanup: Ensure proper cleanup of resources in destruction methods to prevent memory leaks and resource exhaustion.

Frequently Asked Questions

When Does the Spring Bean Life Cycle Begin?

The Spring bean life cycle begins when the Spring container is initialized and starts to create and manage beans defined within the application context, typically during the startup phase of the Spring application.

How does managing the bean life cycle improve application performance?

Proper life cycle management ensures efficient resource utilization, preventing memory leaks and ensuring that beans are initialized and destroyed at appropriate times.

Can we mix different life cycle management methods in the same application?

Yes, you can mix methods, but it's generally recommended to stick to one for consistency and maintainability.

Are annotations always the best choice for life cycle management?

While annotations are convenient and reduce boilerplate code, the best choice depends on the specific needs and architecture of your application. In some cases, XML or programmatic configuration might be more suitable.

Conclusion

Understanding and implementing the bean life cycle in Java Spring is crucial for creating efficient and robust Spring applications. Each method—XML configuration, programmatic approach, and annotation-based approach—has its advantages and disadvantages. Choosing the right method depends on the application's specific needs, existing architecture, and the development team's preferences. By mastering these methods, developers can ensure that beans in their Spring applications are managed effectively throughout their life cycle.

You can refer to our guided paths on Code360. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. 

Also, check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Live masterclass