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.
Note: We can choose 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 message on start and close of Spring container. Therefore, the three ways to implement this are:
- By XML: In this approach, in order to avail custom init() and destroy() method for a bean we have to register these two methods inside Spring XML configuration file while defining a bean. Therefore, the following steps are followed:
- Firstly, we need to create a bean HelloWorld.java in this case and write the init() and destroy() methods in the class.
// Java program to create a bean// in the spring frameworkpackagebeans;publicclassHelloWorld {// This method executes// automatically as the bean// is instantiatedpublicvoidinit()throwsException{System.out.println("Bean HelloWorld has been "+"instantiated and I'm "+"the init() method");}// This method executes// when the spring container// is closedpublicvoiddestroy()throwsException{System.out.println("Conatiner has been closed "+"and I'm the destroy() method");}}chevron_rightfilter_none - Now, we need to configure the spring XML file spring.xml and need to register the init() and destroy() methods in it.
<!DOCTYPEbeans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"<beans><beanid="hw"class="beans.HelloWorld"init-method="init"destroy-method="destroy"/></beans>chevron_rightfilter_none - Finally, we need to create a driver class to run this bean.
// Java program to call the// bean initialized abovepackagetest;importorg.springframework.context.ConfigurableApplicationContext;importorg.springframework.context.support.ClassPathXmlApplicationContext;importbeans.HelloWorld;// Driver classpublicclassClient {publicstaticvoidmain(String[] args)throwsException{// Loading the Spring XML configuration// file into the spring container and// it will create the instance of// the bean as it loads into containerConfigurableApplicationContext cap=newClassPathXmlApplicationContext("resources/spring.xml");// It will close the spring container// and as a result invokes the// destroy() methodcap.close();}}chevron_rightfilter_noneOutput:
Bean HelloWorld has been instantiated and I’m the init() method
Conatiner has been closed and I’m the destroy() method
- Firstly, we need to create a bean HelloWorld.java in this case and write the init() and destroy() methods in the class.
- 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 container is closed.
Note: To invoke destroy method we have to call 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 program to create a bean// in the spring frameworkpackagebeans;importorg.springframework.beans.factory.DisposableBean;importorg.springframework.beans.factory.InitializingBean;// HelloWorld class which implements the// interfacespublicclassHelloWorldimplementsInitializingBean,DisposableBean {@Override// It is the init() method// of our bean and it gets// invoked on bean instantiationpublicvoidafterPropertiesSet()throwsException{System.out.println("Bean HelloWorld has been "+"instantiated and I'm the "+"init() method");}@Override// This method is invoked// just after the container// is closedpublicvoiddestroy()throwsException{System.out.println("Conatiner has been closed "+"and I'm the destroy() method");}}chevron_rightfilter_none - Now, we need to configure the spring XML file spring.xml and define the bean.
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"<beans><beanid="hw"class="beans.HelloWorld"/></beans>chevron_rightfilter_none - Finally, we need to create a driver class to run this bean.
// Java program to call the// bean initialized abovepackagetest;importorg.springframework.context.ConfigurableApplicationContext;importorg.springframework.context.support.ClassPathXmlApplicationContext;importbeans.HelloWorld;// Driver classpublicclassClient {publicstaticvoidmain(String[] args)throwsException{// Loading the Spring XML configuration// file into the spring container and// it will create the instance of the bean// as it loads into containerConfigurableApplicationContext cap=newClassPathXmlApplicationContext("resources/spring.xml");// It will close the spring container// and as a result invokes the// destroy() methodcap.close();}}chevron_rightfilter_noneOutput:
Bean HelloWorld has been instantiated and I’m the init() method
Conatiner has been closed and I’m the destroy() method
- Firstly, we need to create a bean HelloWorld.java in this case by implementing InitializingBean, DisposableBean and overriding afterPropertiesSet() and destroy() method.
- 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 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 program to create a bean// in the spring frameworkpackagebeans;importjavax.annotation.PostConstruct;importjavax.annotation.PreDestroy;// HelloWorld classpublicclassHelloWorld {// Annotate this method to execute it// automatically as the bean is// instantiated@PostConstructpublicvoidinit()throwsException{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@PreDestroypublicvoiddestroy()throwsException{System.out.println("Conatiner has been closed "+"and I'm the destroy() method");}}chevron_rightfilter_none - Now, we need to configure the spring XML file spring.xml and define the bean.
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"<beans><!-- activate the @PostConstruct and@PreDestroy annotation --><beanclass="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor"/><!-- cofigure the bean --><beanclass="beans.HelloWorld"/></beans>chevron_rightfilter_none - Finally, we need to create a driver class to run this bean.
// Java program to call the// bean initialized abovepackagetest;importorg.springframework.context.ConfigurableApplicationContext;importorg.springframework.context.support.ClassPathXmlApplicationContext;importbeans.HelloWorld;// Driver classpublicclassClient {publicstaticvoidmain(String[] args)throwsException{// Loading the Spring XML configuration// file into Spring container and// it will create the instance of the// bean as it loads into containerConfigurableApplicationContext cap=newClassPathXmlApplicationContext("resources/spring.xml");// It will close the Spring container// and as a result invokes the// destroy() methodcap.close();}}chevron_rightfilter_noneOutput:
Bean HelloWorld has been instantiated and I’m the init() method
Conatiner has been closed and I’m the destroy() method
- 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.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
Recommended Posts:
- Singleton and Prototype Bean Scopes in Java Spring
- Life cycle of JSP
- Life Cycle of a Servlet
- Spring Boot | How to access database using Spring Data JPA
- Spring vs. Struts in Java
- Spring MVC using Java based configuration
- How to create a REST API using Java Spring Boot
- How to create a basic application in Java Spring Boot
- Containerizing Java applications | Creating a Spring Boot App using Dockerfile
- Spring Dependency Injection with Example
- Introduction to Spring Framework
- Introduction to Spring Boot
- Introduction to the Spring Data Framework
- Aspect Oriented Programming and AOP in Spring Framework
- How to encrypt passwords in a Spring Boot project using Jasypt
- Spring Boot | How to consume JSON messages using Apache Kafka
- Spring Boot | How to publish String messages on Apache Kafka
- Spring Boot | How to consume string messages using Apache Kafka
- Spring Boot | How to publish JSON messages on Apache Kafka
- Java.util.LinkedList.poll(), pollFirst(), pollLast() with examples in Java
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


