spring

Spring init-method and destroy-method Tutorial

Sometimes when the spring beans are created developers need to perform the initialization operations and the cleanup operations before the bean is destroyed. In the spring framework, we can use the init-method and the destroy-method tags in the bean configuration. This tutorial will explore these tags to briefly understand the initialization and destruction.
 
 
 
 
 
 
 

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 init-method - Spring bean lifecycle
Fig. 1: Spring bean lifecycle

Now, open up the Eclipse IDE and let us see how to implement the init-method and the destroy-method tags in the spring framework!

2. Spring init-method and destroy-method Tutorial

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, MySQL 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 init-method - 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 init-method - 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 init-method - 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 init-method - 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</groupId>
	<artifactId>SpringLifecycleExample1</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</groupId>
	<artifactId>SpringLifecycleExample1</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>
	<dependencies>
		<!-- Spring Framework Dependencies -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>5.1.0.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>5.1.0.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 Bean class

Add the following code to the bean definition:

IciciAtm.java

package com.spring.model;

public class IciciAtm {

	String welcomemsg;

	public void init() {
		System.out.println("ATM init method called. Connecting to bank's network.");
	}

	public void destroy() {
		System.out.println("ATM destroy method called. Disconnecting from bank's network.");
	}

	public String getWelcomemsg() {
		return welcomemsg;
	}

	public void setWelcomemsg(String welcomemsg) {
		this.welcomemsg = welcomemsg;
	}
}

3.2.2 Implementation of Utility Class

The implementation class will be able to load the bean definition from the bean configuration file. Add the following code to it:

AppMain.java

package com.spring.util;

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

import com.spring.model.IciciAtm;

public class AppMain {

	public static void main(String[] args) {

		System.out.println("************** Begin Program **************");

		AbstractApplicationContext ac = new ClassPathXmlApplicationContext("spring-lifecycle.xml");

		IciciAtm atm = ac.getBean(IciciAtm.class);	
		System.out.println(atm.getWelcomemsg());

		// closing the context object!
		ac.close();

		System.out.println("************** End Program **************");
	}
}

3.3 Bean Configuration file

In the spring xml configuration, we can configure the initialization and destruction methods using the init-method and destroy-method attributes of the <bean /> element.

spring-lifecycle.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-3.0.xsd">

	<!-- Atm bean definition -->
	<bean id="atm" class="com.spring.model.IciciAtm" init-method="init"
		destroy-method="destroy">

		<property name="welcomemsg" value="Welcome to Icici bank Atm" />
	</bean>
</beans>

4. Run the Application

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

Spring init-method - Run the Application
Fig. 6: Run the Application

5. Project Demo

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

/* Output logs of the application */

************** Begin Program **************
ATM init method called. Connecting to bank's network.
Welcome to Icici bank Atm
ATM destroy method called. Disconnecting from bank's network.
************** End Program **************

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 the spring bean using the xml configuration tags. Always remember, you must specify the method names that have a void no-argument signature.

6.1 Trailing notes

If there are multiple beans in the configuration file that needs to perform the initialization and destruction activities, and all the beans have the same method signature, under those circumstances, it is advisable to define them using the default-init-method and default-destroy-method tags.

<?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-3.0.xsd"
	default-init-method="init" default-destroy-method="destroy">

	<!-- Bean definitions -->
</beans>

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 init-method and destroy-method.

Download
You can download the full source code of this example here: SpringLifecycleExample1

Yatin

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Gregory P Patnude
5 years ago

While your solution works, it only works if you adopt the Spring-framework… Many people, including myself prefer a solution that is independent of a particular framework and just works.

You don’t need all the overhead of the XML-Configuration and Bean-wiring and the Spring framework if you just use the @PostConstruct and @PreDestroy annotations — these has been part of core-Java since 1.5 and also avoids any framework dependencies on Spring.

@PostConstruct
public void init() {

System.out.println(“ATM init method called. Connecting to bank’s network.”);

}

@PreDestroy
public void destroy() {

System.out.println(“ATM destroy method called. Disconnecting from bank’s network.”);

}

Back to top button