Spring InitializingBean And DisposableBean

When creating an instance of a bean you might need to do some initialization to the bean. Similarly, when the bean is no longer needed and removed from the Spring container you might want to do some cleanup routine or destroy the bean. To do this initialization and destroy routine you need to implements the InitializingBean and DisposableBean. These interfaces is located under the org.springframework.beans.factory package.

Following example demonstrates how to use InitializingBean and DisposableBean

First create a new Java Project and configure it as Maven Project. For Reference, Click Here

Add the following dependencies in pom.xml



Create Employee Class as following

package com.kruders.bean;

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

public class Employee implements InitializingBean, DisposableBean{
	private String name;
    public String getName() {
        return name;
    public void setName(String name) {
        this.name = name;
    public void afterPropertiesSet() throws Exception {
    	System.out.println("Init method called: ");
    public void destroy() throws Exception {
  	  	System.out.println("Destroy method called: ");

The InitializingBean interface can be used and has a method signature of public void afterPropertiesSet() throws Exception. The destruction lifecycle event’s interface is DisposableBean and it’s method signature is public void destroy() throws Exception.

2. Configuration

Create Spring-Bean.xml and write the following code

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

	<bean id="employee" class="com.kruders.bean.Employee">
        <property name="name" value="Puneet" />


3. Run Program

Create Main.java class and run it as Java Application

package com.kruders.core;

import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.kruders.bean.Employee;
public class Main {
    public static void main(String[] args) {
    	ConfigurableApplicationContext context = new ClassPathXmlApplicationContext(
        Employee employee = (Employee) context.getBean("employee");
        System.out.println("Name " + employee.getName());

When you run the above example you’ll get an output like:

Init method called:
Name Puneet
Destroy method called:

The folder structure of the example is shown below in Figure 53.1

Figure 53.1 Figure 53.1

You can download the source code of this example here.

No comments yet.

Leave a Reply