Spring中关于bean的销毁有三种方法。分别是1)执行某一方法如destroy()方法,然后在<bean>标签上的destroy-method属性制定方法名就行了。2)实现DisopableBean接口的destroy方法,DispoableBean接口只有一个destroy方法,在bean销毁前调用。代码如下:
public class DestructiveBeanImpl implements DisposableBean{
public void destroy(){
//System.out.println("销毁bean");//计入日志等代码
}
}
3)使用关闭钩子shutdownHook来进行销毁Bean。Spring销毁回调的唯一确定是他们不能被自动出发,要记得在应用关闭之前调用destroySingletons()方法。在java中允许创建一个关闭钩子,他是一个刚好在应用关闭前会被执行的一个线程。这是一个调用BeanFactory的destroySingletons方法的最佳途径。最简单的方法就是创建一个实现了Runnable接口的类,并在run()方法中调用destroySingletons()。代码清单如下:
public class ShutdownHook implements Runnable{
private ConfigurableListableBeanFactory beanfactory;
public ShudownHook(ConfigurableListableBeanFactory beanfactory){
Assert.notNull(beanfactroy, "The 'beanfactory' argument must not be null." );
this.beanfactory = beanfactory;
}
public void run(){ //重写Runnable中的run方法并在此销毁bean
this.beanfactory.destroySingletons();
}
}
注册关闭钩子代码如下:
public class ShtdownHookDemo {
public static void main(String[] args) throws IOException {
XmlBeanFactory factory = new XmlBeanFactory( new ClassPathResource( "/META-INF/spring/lifecycle-context.xml"));
Runtime.getRuntime().addShutdownHook( nwe Thread( new ShutdownHook(factory))); //得到Runtime的引用并注册关闭钩子
new BufferendInputStream(System.in).read();
}
}
最后destroySingletons()方法确实已被调用,尽管我们并未编写任何代码在应用程序要关闭时明确调用的该方法。这就是模板方法设计模式中的钩子。