In Spring, InitializingBean and DisposableBean are two marker interfaces, a useful way for Spring to perform certain actions upon bean initialization and destruction.
- For bean implemented InitializingBean, it will run
afterPropertiesSet()
after all bean properties have been set. - For bean implemented DisposableBean, it will run
destroy()
after Spring container is released the bean.
Example
package org.kodejava.example.spring;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
public class InitDisposeService
implements InitializingBean, DisposableBean {
/**
* Do some processes.
*/
public void doSomething() {
System.out.println("InitDisposeService.doSomething");
}
/**
* Initialize bean after property set.
*
* @throws Exception
*/
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("InitDisposeService.afterPropertiesSet");
}
/**
* Clean-up bean when the context is closed.
*
* @throws Exception
*/
@Override
public void destroy() throws Exception {
System.out.println("InitDisposeService.destroy");
}
}
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.
File : Spring-Customer.xml
<?xml version="1.0" encoding="UTF-8"?>
<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-3.0.xsd">
<bean id="service" class="org.kodejava.example.spring.InitDisposeService"/>
</beans>
Run it
package org.kodejava.example.spring;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class InitDisposeDemo {
public static void main(String[] args) {
ConfigurableApplicationContext context =
new ClassPathXmlApplicationContext("InitDispose.xml");
InitDisposeService service =
(InitDisposeService) context.getBean("service");
service.doSomething();
context.close();
}
}
The ConfigurableApplicationContext.close() will close the application context, releasing all resources and destroying all cached singleton beans. It’s use fordestroy()
method demo purpose only :)
Output
InitDisposeService.afterPropertiesSet
InitDisposeService.doSomething
InitDisposeService.destroy
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 theinit-method and destroy-method attributes in your bean configuration file. see http://blog.csdn.net/gloomuu/article/details/8588380