The Wayback Machine - https://web.archive.org/web/20240620070904/https://www.geeksforgeeks.org/bean-life-cycle-in-java-spring/
Open In App

Bean life cycle in Java Spring

Last Updated : 18 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Pre-requisite: Introduction to Spring Framework

The lifecycle of any object means when & how it is born, how it behaves throughout its life, and when & how it dies. Similarly, the bean life cycle refers to when & how the bean is instantiated, what action it performs until it lives, and when & how it is destroyed. In this article, we will discuss the life cycle of the bean. 

Bean life cycle is managed by the spring container. When we run the program then, first of all, the spring container gets started. After that, the container creates the instance of a bean as per the request, and then dependencies are injected. And finally, the bean is destroyed when the spring container is closed. Therefore, if we want to execute some code on the bean instantiation and just after closing the spring container, then we can write that code inside the custom init() method and the destroy() method.

The following image shows the process flow of the bean life cycle.  

Bean Life Cycle Process Flow

Note: We can choose a custom method name instead of init() and destroy(). Here, we will use init() method to execute all its code as the spring container starts up and the bean is instantiated, and destroy() method to execute all its code on closing the container. 

Ways to implement the life cycle of a bean

Spring provides three ways to implement the life cycle of a bean. In order to understand these three ways, let’s take an example. In this example, we will write and activate init() and destroy() method for our bean (HelloWorld.java) to print some messages on start and close of the Spring container. Therefore, the three ways to implement this are: 

1. By XML: In this approach, in order to avail custom init() and destroy() methods for a bean we have to register these two methods inside the Spring XML configuration file while defining a bean. Therefore, the following steps are followed: 

Step 1: Firstly, we need to create a bean HelloWorld.java in this case and write the init() and destroy() methods in the class.

Java




// Java program to create a bean
// in the spring framework
package beans;
 
public class HelloWorld {
 
    // This method executes
    // automatically as the bean
    // is instantiated
    public void init() throws Exception
    {
        System.out.println(
            "Bean HelloWorld has been "
            + "instantiated and I'm "
            + "the init() method");
    }
 
    // This method executes
    // when the spring container
    // is closed
    public void destroy() throws Exception
    {
        System.out.println(
            "Container has been closed "
            + "and I'm the destroy() method");
    }
}


Step 2: Now, we need to configure the spring XML file spring.xml and need to register the init() and destroy() methods in it.

XML




<!DOCTYPE
    beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
             
<beans>
    <bean id="hw" class="beans.HelloWorld"
            init-method="init" destroy-method="destroy"/>
     
</beans>


Step 3: Finally, we need to create a driver class to run this bean.

Java




// Java program to call the
// bean initialized above
 
package test;
 
import beans.HelloWorld;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
// Driver class
public class Client {
 
    // Main driver method
    public static void main(String[] args) throws Exception
    {
 
        // Loading the Spring XML configuration
        // file into the spring container and
        // it will create the instance of
        // the bean as it loads into container
 
        ConfigurableApplicationContext cap
            = new ClassPathXmlApplicationContext(
                "resources/spring.xml");
 
        // It will close the spring container
        // and as a result invokes 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 

2. By Programmatic Approach: To provide the facility to the created bean to invoke custom init() method on the startup of a spring container and to invoke the custom destroy() method on closing the container, we need to implement our bean with two interfaces namely InitializingBean, DisposableBean and will have to override afterPropertiesSet() and destroy() method. afterPropertiesSet() method is invoked as the container starts and the bean is instantiated whereas, the destroy() method is invoked just after the container is closed. 

Note: To invoke destroy method we have to call a close() method of ConfigurableApplicationContext.

Therefore, the following steps are followed: 

  • Firstly, we need to create a bean HelloWorld.java in this case by implementing InitializingBean, DisposableBean, and overriding afterPropertiesSet() and destroy() method.

Java




// Java program to create a bean
// in the spring framework
package beans;
 
import org.springframework
    .beans.factory.DisposableBean;
 
import org.springframework
    .beans.factory.InitializingBean;
 
// HelloWorld class which implements the
// interfaces
public class HelloWorld
    implements InitializingBean,
 DisposableBean {
 
    @Override
    // It is the init() method
    // of our bean and it gets
    // invoked on bean instantiation
    public void afterPropertiesSet()
throws Exception
    {
        System.out.println(
            "Bean HelloWorld has been "
            + "instantiated and I'm the "
            + "init() method");
    }
 
    @Override
    // This method is invoked
    // just after the container
    // is closed
    public void destroy() throws Exception
    {
        System.out.println(
            "Container has been closed "
            + "and I'm the destroy() method");
    }
}


  • Now, we need to configure the spring XML file spring.xml and define the bean.

XML




<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
             
<beans>
    <bean id="hw" class="beans.HelloWorld"/>
     
</beans>


  • Finally, we need to create a driver class to run this bean.

Java




// Java program to call the
// bean initialized above
 
package test;
 
import org.springframework
    .context
    .ConfigurableApplicationContext;
 
import org.springframework
    .context.support
    .ClassPathXmlApplicationContext;
 
import beans.HelloWorld;
 
// Driver class
public class Client {
 
    public static void main(String[] args)
        throws Exception
    {
 
        // Loading the Spring XML configuration
        // file into the spring container and
        // it will create the instance of the bean
        // as it loads into container
        ConfigurableApplicationContext cap
            = new ClassPathXmlApplicationContext(
                "resources/spring.xml");
 
        // It will close the spring container
        // and as a result invokes 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 
 

3. Using Annotation: 

To provide the facility to the created bean to invoke custom init() method on the startup of a spring container and to invoke the custom destroy() method on closing the container, we need to annotate init() method by @PostConstruct annotation and destroy() method by @PreDestroy annotation.

Note: To invoke the destroy() method we have to call the close() method of ConfigurableApplicationContext.

Therefore, the following steps are followed:

  • Firstly, we need to create a bean HelloWorld.java in this case and annotate the custom init() method with @PostConstruct and destroy() method with @PreDestroy.

Java




// Java program to create a bean
// in the spring framework
package beans;
 
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
 
// HelloWorld class
public class HelloWorld {
 
    // Annotate this method to execute it
    // automatically as the bean is
    // instantiated
    @PostConstruct
    public void init() throws Exception
    {
        System.out.println(
            "Bean HelloWorld has been "
            + "instantiated and I'm the "
            + "init() method");
    }
 
    // Annotate this method to execute it
    // when Spring container is closed
    @PreDestroy
    public void destroy() throws Exception
    {
        System.out.println(
            "Container has been closed "
            + "and I'm the destroy() method");
    }
}


  • Now, we need to configure the spring XML file spring.xml and define the bean.

XML




<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
             
<beans>
 
    <!-- activate the @PostConstruct and
@PreDestroy annotation -->
 
    <bean class="org.springframework
.context.annotation
.CommonAnnotationBeanPostProcessor"/>
 
    <!-- configure the bean -->
    <bean class="beans.HelloWorld"/>
     
</beans>


  • Finally, we need to create a driver class to run this bean.

Java




// Java program to call the
// bean initialized above
 
package test;
 
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import beans.HelloWorld;
 
// Driver class
public class Client {
 
    // Main driver method
    public static void main(String[] args) throws Exception
    {
 
        // Loading the Spring XML configuration
        // file into Spring container and
        // it will create the instance of the
        // bean as it loads into container
        ConfigurableApplicationContext cap
            = new ClassPathXmlApplicationContext(
                "resources/spring.xml");
 
        // It will close the Spring container
        // and as a result invokes 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


Previous Article
Next Article

Similar Reads

Singleton and Prototype Bean Scopes in Java Spring
Bean Scopes refers to the lifecycle of Bean that means when the object of Bean will be instantiated, how long does that object live, and how many objects will be created for that bean throughout. Basically, it controls the instance creation of the bean and it is managed by the spring container.Bean Scopes in Spring The spring framework provides fiv
8 min read
Spring MessageSourceAware Java Bean Example
MessageSourceAware in Spring can be used to implement internationalization in Java. If different locales have to be implemented in a web application, then configuring different resources can be performed using MessageSourceAware. So, let's see how we can configure Java Bean that implements MessageSourceAware. Prerequisite TopicSpring: Spring is a J
3 min read
How to Create a Spring Bean in 3 Different Ways?
Spring is one of the most popular Java EE frameworks. It is an open-source lightweight framework that allows Java EE 7 developers to build simple, reliable, and scalable enterprise applications. This framework mainly focuses on providing various ways to help you manage your business objects. It made the development of Web applications much easier t
5 min read
Spring @Bean Annotation with Example
One of the most important annotations in spring is the @Bean annotation which is applied on a method to specify that it returns a bean to be managed by Spring context. Spring Bean annotation is usually declared in Configuration classes methods. This annotation is also a part of the spring core framework. So let's understand @Bean Annotation with an
8 min read
Spring - Inheriting Bean
Constructor arguments, property values, and container-specific information like initialization method, static factory method name, and so on may all be found in a bean definition. A parent definition's configuration data is passed down to a child bean definition. The child definition has the ability to override or add values as needed. Although Spr
3 min read
Custom Bean Scope in Spring
Prerequisite: Singleton and Prototype Bean Scopes in Java Spring In this article, we are going to discuss the custom bean scope in Spring. I presume that you guys know about Spring bean and its scopes provided by Spring framework. A bean is an object that is instantiated, assembled, and otherwise managed by a Spring IoC container. Spring provides t
5 min read
Spring Bean Validation - JSR-303 Annotations
In this article, we'll explore practical examples of how to apply JSR-303 annotations to your domain objects from basic annotations to advanced. So basically annotations provide a declarative way to configure Spring beans, manage dependencies, and define behaviors, reducing the need for boilerplate code and making your code more concise and express
6 min read
Spring Boot - Spring JDBC vs Spring Data JDBC
Spring JDBC Spring can perform JDBC operations by having connectivity with any one of jars of RDBMS like MySQL, Oracle, or SQL Server, etc., For example, if we are connecting with MySQL, then we need to connect "mysql-connector-java". Let us see how a pom.xml file of a maven project looks like. C/C++ Code &lt;?xml version=&quot;1.0&quot; encoding=
4 min read
Difference Between Spring DAO vs Spring ORM vs Spring JDBC
The Spring Framework is an application framework and inversion of control container for the Java platform. The framework's core features can be used by any Java application, but there are extensions for building web applications on top of the Java EE platform. Spring-DAO Spring-DAO is not a spring module. It does not provide interfaces or templates
5 min read
Spring vs Spring Boot vs Spring MVC
Are you ready to dive into the exciting world of Java development? Whether you're a seasoned pro or just starting out, this article is your gateway to mastering the top frameworks and technologies in Java development. We'll explore the Spring framework, known for its versatility and lightweight nature, making it perfect for enterprise-level softwar
8 min read
Article Tags :
Practice Tags :