Spring Bean Life Cycle

In this tutorial, we are going to learn about the Spring bean life cycle. It is root of Spring framework or to get into any IT company or to make any product in proper way in Spring.

Definition:

The sequence of changes which occurs in the spring bean is called spring bean life cycle from its initialization to its destruction. Spring life cycle tells us about how Spring bean will be maintained by Spring IOC Container. If you have not covered basics of spring then please covers basics by reading our previous articles.

Methods for it:

It is really easy to understand about Spring bean life cycle. When Spring IOC container invoke the bean object, then it is needed to do some initialization steps to establish usable stage. When that initialized bean is not usable then it is removed by spring IOC container. There are a lot of different processes among invocation and removal of that spring bean object. These processes take place in the backend. These are following stages in life cycle of any Spring bean.

  1. Objectification – Spring IOC container instantiate that specified bean.
  2. Injection of Bean’s Properties – Spring IoC container injects the bean’s properties.
  3. Setting of Bean Name – In this process Spring IOC container puts that specified bean name.
  4. Setting of Bean Factory – In this process Spring IOC container calls method setBeanFactory().
  5. Calling of Pre Initialization – Pre initialization of bean is also known by name of postprocess of bean. In this Spring IOC container calls method named postProcesserBeforeInitialization().
  6. Calling of Initialize Beans – When that specified bean implements interface IntializingBean, then Spring IOC container calls method named afterPropertySet(). When that spring bean has declaration of init method then that provided method is called by Spring IOC named initialization.
  7. Calling of Post Initialization – In this process Spring IOC container calls method postProcessAfterinitalization().
  8. Bean is Settled for usage – Now we have spring bean object which we can use for our application processes.
  9. Removal of that Bean – In this process Spring IOC container calls method destroy() of interface DisposableBean.

Spring Bean Life Cycle

Image Source

Spring Bean Life Cycle

Below is an example to demonstrate bean life cycle.

Import Project in Eclipse

If you are familiar with eclipse then just download source code of this application from here https://github.com/shubhamsharmacs/BeanLifeCycleSpring. Then import it inside eclipse IDE by going towards.

File -> Import -> Existing Maven Project -> Browse (Go towards your downloaded code) -> Select All -> Finish

SBLC

If you will explore the project then you will see these folders:

  • /src/main/java folder, it has all java related source files
  • /src/test/java folder, it has all java related test files
  • /src/main/resources, it has all configuration related files
  • /target folder, after running it will contains all packaging related files of our application
  • the pom.xml, this file contains all our libraries or spring framework related configurations.

Open Pom.xml file in Eclipse

Here we had added Maven maintain library and dependencies related stuff.

If you will see <properties> section, here you have to put spring framework version number.

If you will go towards <dependencies> section then you have to add required dependencies for this example.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.shubham.snippets.enterprise</groupId>
	<artifactId>LifeCycleBean</artifactId>
	<version>0.0.1-SNAPSHOT</version>


	<dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${spring.version}</version>
		</dependency>
	</dependencies>

	<properties>
		<spring.version>3.2.3.RELEASE</spring.version>
	</properties>
</project>

Using InitializingBean and DisposableBean Interfaces

If you will open Teacher bean in services folder then it has implemented interface called InitializingBean (method is afterPropertiesSet()), reason for using this interface is for doing initialization stuff when all needed properties on bean had putted by spring IOC container. Now if we will go towards interface called DisposableBean (method is destroy ()) then it will be called when that bean object is going to destroyed by spring IOC container.

@SuppressWarnings("restriction")
public class Teacher implements InitializingBean, DisposableBean{
	
	private Long id;

	private String position;
	
	//here we had defined our getters and setters for setting id and position properties
	
	// here we are putting our destroy() method of DisposableBean  and init method of InitializingBean 
	public void destroy() throws Exception {
		System.out.println("IOC container calling from destroy() for cleaning object");
	}

	public void afterPropertiesSet() throws Exception {
		System.out.println("doing initialization stuff afterPropertiesSet()");	
	}
	
}

Using init Method and destroy Method

The Teacher bean object is created below implements both interfaces and uses their methods to print a message each time the bean is created and destroyed.

@SuppressWarnings("restriction")
public class Teacher {
	
	private Long id;
	private String position;
	
	//here we had defined our getters and setters for setting id and position properties
	
	// here we are putting our initIt() and cleanUp methods defined in application context  
	
		public void initIt() throws Exception {
		  System.out.println("Spring IOC container calling from Init method");
		}
	
	public void cleanUp() throws Exception {
		  System.out.println("container calling from cleanup() for cleaning object ");
		}
}

applicationContext.xml

The bean is defined with its properties in applicationContext.xml.

<context:annotation-config />
		<bean id="TeacherBean" class="com.shubham.snippets.enterprise.services.Teacher" init-method="initIt" destroy-method="cleanUp">
		<property name="id" value="123"/>
		<property name="position" value="HeadOfDepartment"/>
	</bean>

App.java

From App.java class we actually load our bean. Here is code for the same.

public class App {
        public static void main(String[] args) {
                              ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
                              Teacher em = (Teacher) context.getBean("TeacherBean");
                              System.out.println(em.toString());
                                             context.close();
        }
}

When the application is executed the result is the one shown below:

Output

Nov 13, 2017 9:02:32 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons

INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@64616ca2: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,TeacherBean,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor]; root of factory hierarchy

IOC container calling from Init method Nov 13, 2017 9:02:32 PM org.springframework.context.support.AbstractApplicationContext doClose

INFO: Closing org.springframework.context.support.ClassPathXmlApplicationContext@76fb509a: startup date [Mon Nov 13 21:02:32 IST 2017]; root of context hierarchy

id 123 and position HeadOfDepartment

container calling from cleanup() for cleaning object.

Nov 13, 2017 9:02:32 PM org.springframework.beans.factory.support.DefaultSingletonBeanRegistry destroySingletons

INFO: Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@64616ca2: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,TeacherBean,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor]; root of factory hierarchy

Exploration of Output

Now if you can see this line “IOC container calling from Init method Nov 13, 2017 9:02:32 PM org.springframework.context.support.AbstractApplicationContext doClose”, here your spring bean life cycle is initialized. And in this line “Spring Clean Up! Teacher Object is cleaned up now.”, here your spring bean life cycle is destroyed.

About Author:

Shubham Sharma, currently working as Analytics Engineer in Data Science Domain. Has around 2+ years of experience in Data Science. Skilled in Python, Pandas, Anaconda, Tensorflow, Keras, Scikit learn, Numpy, Scipy, Microsoft Excel, SQL, Cassandra and Statistical Data Analysis, Hadoop, Hive, Pig, Spark, Pyspark. Connect with him at shubhamsharma1318@gmail.com.

Leave a Comment

Your email address will not be published. Required fields are marked *