In Spring, you can use init-method and destroy-method as attribute in bean configuration file for bean to perform certain actions upon initialization and destruction. Alternative to InitializingBean and DisposableBean interface.


Here’s an example to show you how to use init-method and destroy-method.


public class CustomerService
	String message;
	public String getMessage() {
	  return message;

	public void setMessage(String message) {
	  this.message = message;
	public void initIt() throws Exception {
	  System.out.println("Init method after properties are set : " + message);
	public void cleanUp() throws Exception {
	  System.out.println("Spring Container is destroy! Customer clean up");

File : Spring-Customer.xml, define init-method and destroy-method attribute in your bean.

<beans xmlns=""

	<bean id="customerService" class="" 
		init-method="initIt" destroy-method="cleanUp">
		<property name="message" value="i'm property message" />

Run it

package com.mkyong.common;

import org.springframework.context.ConfigurableApplicationContext;


public class App 
    public static void main( String[] args )
    	ConfigurableApplicationContext context = 
		new ClassPathXmlApplicationContext(new String[] {"Spring-Customer.xml"});
    	CustomerService cust = (CustomerService)context.getBean("customerService");

The ConfigurableApplicationContext.close will close the application context, releasing all resources and destroying all cached singleton beans.


Init method after properties are set : i'm property message
INFO: Destroying singletons in org.springframework.beans.factory.
defining beans [customerService]; root of factory hierarchy
Spring Container is destroy! Customer clean up

The initIt() method is called, after the message property is set, and the cleanUp() method is called after the context.close();

It’s always recommended to use init-method and destroy-method in bean configuration file, instead of implement the InitializingBean and DisposableBean interface to cause unnecessarily coupled your code to Spring.

Download Source Code