Spring InitializingBean and DisposableBean

In Spring, InitializingBean and DisposableBean are two marker interfaces, a useful way for Spring to perform certain actions upon bean initialization and destruction.

  1. For bean implemented InitializingBean, it will run afterPropertiesSet() after all bean properties have been set.
  2. For bean implemented DisposableBean, it will run destroy() after Spring container is released the bean.


Here’s an example of  how to use InitializingBean and DisposableBean. A Test bean to implement both InitializingBean and DisposableBean interface, and has a message property.

package com.javabrown.sample;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
public class TestBean implements InitializingBean, DisposableBean
	String message;
	public String getMessage() {
	  return message;
	public void setMessage(String message) {
	  this.message = message;
	public void afterPropertiesSet() throws Exception {
	  System.out.println("init() on after properties are set : "
              + message);
	public void destroy() throws Exception {
             "Spring Container is destroy! TestBean cleaned");

File : Spring-Test.xml

       <bean id="test-bean" class="com.javabrown.sample.TestBean">
		<property name="message" value="Hello World" />

Run TestBean

package com.javabrown.sample;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.javabrown.TestBean;
public class BeanTester 
    public static void main( String[] args )
    	ConfigurableApplicationContext context = 
	    new ClassPathXmlApplicationContext(
                 new String[] {"Spring-Test.xml"});
    	TestBean tester= (TestBean)context.getBean("test-bean");

The context.close() will close the application context, releasing all resources and destroying all cached singleton beans. It’s use to show you the demo of  destroy() method.


Init method after properties are set : im property message
INFO: Destroying singletons in org.springframework.beans.factory.
defining beans [test-bean]; root of factory hierarchy
Spring Container is destroy! TestBean cleaned