Home » Enterprise Java » spring » Spring Bean Life-Cycle Example

About Yatin

Yatin
The author is graduated in Electronics & Telecommunication. During his studies, he has been involved with a significant number of projects ranging from programming and software engineering to telecommunications analysis. He works as a technical lead in the information technology sector where he is primarily involved with projects based on Java/J2EE technologies platform and novel UI technologies.

Spring Bean Life-Cycle Example

Sometimes when the spring beans are created developers need to perform the initialization and the cleanup operations before the bean is destroyed. To achieve this, we can use the InitializingBean and the DisposableBean interfaces in the spring model classes. This tutorial will explore these callback interfaces to briefly understand the initialization and destruction process in the spring framework.

1. Introduction

  • Spring is an open-source framework created to address the complexity of an enterprise application development
  • One of the chief advantages of the Spring framework is its layered architecture, which allows the developer to be selective about which of its components they can use while providing a cohesive framework for J2EE application development
  • Spring framework provides support and integration to various technologies for e.g.:
      • Support for Transaction Management
      • Support for interaction with the different databases
      • Integration with the Object Relationship frameworks for e.g. Hibernate, iBatis etc
      • Support for Dependency Injection which means all the required dependencies will be resolved with the help of containers
      • Support for REST style web-services

1.1 Spring Bean Lifecycle

Spring bean is responsible for managing the lifecycle of beans created through the spring container. The bean lifecycle consists of post-initialization and pre-destruction callback methods. The following flowchart diagram illustrates the bean lifecycle diagram.

Spring Bean Life-Cycle
Fig. 1: Spring Bean Lifecycle

Now, open the Eclipse IDE and let us see how to implement these callback interfaces in the spring framework!

2. Spring Bean Lifecycle Example

Here is a systematic guide for implementing this tutorial in the spring framework.

2.1 Tools Used

We are using Eclipse Kepler SR2, JDK 8 and Maven. Having said that, we have tested the code against JDK 1.7 and it works well.

2.2 Project Structure

Firstly, let us review the final project structure, in case you are confused about where you should create the corresponding files or folder later!

Spring Bean Life-Cycle - Application Project Structure
Fig. 2: Application Project Structure

2.3 Project Creation

This section will demonstrate how to create a Java-based Maven project with Eclipse. In Eclipse IDE, go to File -> New -> Maven Project.

Spring Bean Life-Cycle - Create a Maven Project
Fig. 3: Create a Maven Project

In the New Maven Project window, it will ask you to select a project location. By default, ‘Use default workspace location’ will be selected. Select the ‘Create a simple project (skip archetype selection)’ checkbox and just click on the next button to proceed.

Spring Bean Life-Cycle - Project Details
Fig. 4: Project Details

It will ask you to ‘Enter the group and the artifact id for the project’. We will input the details as shown in the below image. The version number will be by default: 0.0.1-SNAPSHOT.

Spring Bean Life-Cycle - Archetype Parameters
Fig. 5: Archetype Parameters

Click on Finish and the creation of a maven project is completed. If you observe, it has downloaded the maven dependencies and a pom.xml file will be created. It will have the following code:

pom.xml

<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.spring.bean.lifecycle</groupId>
	<artifactId>Springbeanlifecyle</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>
</project>

We can start adding the dependencies that developers want like Spring Core, Spring Context etc. Let us start building the application!

3. Application Building

Below are the steps involved in developing this application.

3.1 Maven Dependencies

Here, we specify the dependencies for the spring framework. Maven will automatically resolve the rest dependencies such as Spring Beans, Spring Core etc. The updated file will have the following code:

pom.xml

<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.spring.bean.lifecycle</groupId>
	<artifactId>Springbeanlifecyle</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>Spring Bean Lifecycle Example</name>
	<description>An example to understand the bean lifecycle in spring framework.</description>
	<dependencies>
		<!-- https://mvnrepository.com/artifact/org.springframework/spring-beans -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-beans</artifactId>
			<version>5.1.3.RELEASE</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>5.1.3.RELEASE</version>
		</dependency>
	</dependencies>
	<build>
		<finalName>${project.artifactId}</finalName>
	</build>
</project>

3.2 Java Class Creation

Let us write the Java classes involved in this application.

3.2.1 Implementation of Person bean

We have a simple Person bean with one attribute and implements the InitializingBean and DisposableBean interfaces. Add the following code to the bean definition.

Person.java

package com.spring.model;

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

public class Person implements DisposableBean, InitializingBean {

	private String name;

	Person() {
		System.out.println("Constructor of person bean is invoked!");
	}

	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}

	//Bean initialization code
	@Override
	public void afterPropertiesSet() throws Exception {
		System.out.println("Initializing method of person bean is invoked!");
	}

	//Bean destruction code
	@Override
	public void destroy() throws Exception {
		System.out.println("Destroy method of person bean is invoked!");
	}
}

3.2.2 Implementation of Utility Class

Add the following code to the implementation class for testing the lifecycle of a spring bean.

Demoapp.java

package com.spring.main;

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

import com.spring.model.Person;

public class Demoapp {

	public static void main(String[] args) {

		// Reading configuration from the spring configuration file.
		ConfigurableApplicationContext   context = new ClassPathXmlApplicationContext("spring-config.xml");

		Person myperson = context.getBean("personBean", Person.class);

		System.out.println("Name= " + myperson.getName());

		// Closing the context object.
		context.close();
	}
}

3.3 Bean Configuration file

Add the following code to the spring configuration file for injecting the properties of the bean.

spring-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<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 name="personBean" class="com.spring.model.Person">
		<property name="name" value="Jason Clarke" />
	</bean>
</beans>

4. Run the Application

To execute the application, right click on the Demoapp class, Run As -> Java Application. Developers can debug the example and see what happens after every step. Enjoy!

Spring Bean Life-Cycle - Run the Application
Fig. 6: Run the Application

5. Project Demo

The code shows the following log as the output of this tutorial.

Constructor of person bean is invoked!
Initializing method of person bean is invoked!
Name= Jason Clarke
Destroy method of person bean is invoked!

That is all for this tutorial and I hope the article served you whatever you were looking for. Happy Learning and do not forget to share!

6. Conclusion

This post defines the initialization and destruction of a spring bean and helps developers understand the basic configuration required to achieve this. Developers can download the sample application as an Eclipse project in the Downloads section.

7. Download the Eclipse Project

This was an example of spring bean lifecycle for beginners.

Download
You can download the full source code of this example here: Springbeanlifecyle
(+1 rating, 3 votes)
1 Comment Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

1
Leave a Reply

avatar
1 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
sharuk Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
sharuk
Guest
sharuk

please do provide Directory Structure for above Example it will be very useful
for beginners like us we are facing lot of obstacles
hope you understand
ThankYou…