Spring InitializingBean and DisposableBean example

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.

Example

Here’s an example to show you how to use InitializingBeanand DisposableBean. A CustomerService bean to implement both InitializingBean and DisposableBean interface, and has a message property.


package com.mkyong.customer.services;

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

public class CustomerService 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 method after properties are set : " + message);
	}
	
	public void destroy() throws Exception {
	  System.out.println("Spring Container is destroy! Customer clean up");
	}
	
}

File : Spring-Customer.xml


<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-2.5.xsd">

       <bean id="customerService" class="com.mkyong.customer.services.CustomerService">
		<property name="message" value="i'm property message" />
       </bean>
		
</beans>

Run it


package com.mkyong.common;

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

import com.mkyong.customer.services.CustomerService;

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

The ConfigurableApplicationContext.close() will close the application context, releasing all resources and destroying all cached singleton beans. It’s use for destroy() method demo purpose only :)

Output


Init method after properties are set : im property message
com.mkyong.customer.services.CustomerService@47393f
...
INFO: Destroying singletons in org.springframework.beans.factory.
support.DefaultListableBeanFactory@77158a: 
defining beans [customerService]; root of factory hierarchy
Spring Container is destroy! Customer clean up

The afterPropertiesSet() method is called, after the message property is set; while the destroy() method is call after the context.close();

Thoughts…
I would not recommend to use InitializingBean and DisposableBean interface, because it will tight coupled your code to Spring. A better approach should be specifying the init-method and destroy-method attributes in your bean configuration file.

Download Source Code

References

  1. InitializingBean Javadoc
  2. DisposableBean Javadoc

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

Leave a Reply

avatar
newest oldest most voted
shareef
Guest
shareef
javalschool
Guest
javalschool

great Post Sir it is very helpful.very clean explanation

Lasantha
Guest
Lasantha

This is not an objective of having such interfaces. Those are to avoid run time errors. Your Thoughts is correct only for 1st one ( see bellow) .

* Interface to be implemented by beans that need to react once all their

* properties have been set by a BeanFactory: for example, to perform custom

* initialization, or merely to check that all mandatory properties have been set

Sumit Bhatnagar
Guest
Sumit Bhatnagar
dota2pro
Guest
dota2pro

Check the post date of both posts, are you idiot?

Mehdi
Guest
Mehdi

Thanks !

Easy And Simple :)

Himanshu
Guest
Himanshu

We can’t say that InitializaingBean and DisposableBean is marker interface. Because marker interfaces don’t contain any method they give a hit to JVM to call some appropriate method. Both interfaces are contain one method. So, We can’t call it as a merker interface…

Rajesh
Guest
Rajesh

I though the same way… though i did not tried yet, i doubt, its Marker interface, if so, then how Spring container will come to know which is init and destroy method.

Raman
Guest
Raman

That was a mistake and fixed now ..you can refer to https://jira.spring.io/browse/SPR-4499

guest
Guest
guest

Will this work on JBoss? For example if I undeployed or restarted a war file that contains a class that implements DisposableBean, will the destroy() method be called?

Shaswat
Guest
Shaswat

Hi,

Here it is given that
‘InitializingBean and DisposableBean are two marker interfaces’

then from where afterPropertiesSet(), destroy() came ??

How that both is marker Interface ?

Sumit Bhatnagar
Guest
Sumit Bhatnagar

Its copied from rose india website.

An
Guest
An

Please check the date of posting the article.. or check your eye side

trackback
Spring – init-method and destroy-method example

[…] file for bean to perform certain actions upon initialization and destruction. Alternative to InitializingBean and DisposableBean interface.ExampleHere’s an example to show you how to use init-method and destroy-method. […]

trackback
Spring Tutorials | Tutorials

[…] InitializingBean and DisposableBean example Implement both InitializingBean and DisposableBean interface for initialization and destruction feature. […]

trackback
Spring – @PostConstruct and @PreDestroy example | Spring

[…] Written on March 29, 2010 at 1:58 am by mkyong In Spring, you can either implement the InitializingBean and DisposableBean interface or specify the init-method and destroy-method in bean configuration file for the […]