Spring Init-Method And Destroy-Method

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 can use the init-method and destroy-method attribute when declaring a bean in spring configuration using the <bean> element.

Following example demonstrates how to use init-method and destroy-method

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;

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

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" init-method="init" destroy-method="destroy">
        <property name="name" value="Puneet" />


The bean’s init-method attribute can be set with any zero parameter method on the bean to be called for it’s initialization event. The bean’s destroy-method attribute can be set with any zero parameter method on the bean to be called for the destruction event.

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 54.1

Figure 54.1 Figure 54.1

You can download the source code of this example here.

No comments yet.

Leave a Reply