?????????究竟Spring在何時調用destroy-method="close" 這個方法close()呢?終于借助JavaEye找到了答案,原來如果Spring不在Web Container或是EJB Container中的時候,這個方法還是需要我們自己來調用的,具體就是調用BeanFactory的destroySingletons()方法,文檔上的“自動調用”這幾個字真是害我不淺呀,原來自動也是通過Web Container或是EJB Container才可以自動,具體做法就是要實現ServletContextListener這個接口,Spring中已經有具體的實現了:
?
publicclass ContextLoaderListener implements ServletContextListener {?
??????? private ContextLoader contextLoader;?
???????
/**
? ? ? ? * Initialize the root web application context.
? ? ? ? */

? ? ? ? publicvoid contextInitialized(ServletContextEvent event){
? ? ? ? ? ? ? ? this.contextLoader = createContextLoader();
? ? ? ? ? ? ? ? this.contextLoader.initWebApplicationContext(event.getServletContext());
? ? ? ? }?
???????
/**
? ? ? ? * Create the ContextLoader to use. Can be overridden in subclasses.
? ? ? ? * @return the new ContextLoader
? ? ? ? */

? ? ? ? protected ContextLoader createContextLoader(){
? ? ? ? ? ? ? ? returnnew ContextLoader();
? ? ? ? }?
???????
/**
? ? ? ? * Return the ContextLoader used by this listener.
? ? ? ? */

? ? ? ? public ContextLoader getContextLoader(){
? ? ? ? ? ? ? ? return contextLoader;
? ? ? ? }?
???????
/**
? ? ? ? * Close the root web application context.
? ? ? ? */

? ? ? ? publicvoid contextDestroyed(ServletContextEvent event){
? ? ? ? ? ? ? ? this.contextLoader.closeWebApplicationContext(event.getServletContext());
? ? ? ? }

}
當tomcat關閉的時候會自動調用contextDestroyed(ServletContextEvent event)這個方法。在看一下contextLoader的closeWebApplicationContext方法:
?
publicvoid closeWebApplicationContext(ServletContext servletContext)throws ApplicationContextException {
? ? ? ? ? ? ? ? servletContext.log("Closing root WebApplicationContext");
? ? ? ? ? ? ? ? Object wac = servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
? ? ? ? ? ? ? ? if(wac instanceof ConfigurableApplicationContext){
? ? ? ? ? ? ? ? ? ? ? ? ((ConfigurableApplicationContext) wac).close();
? ? ? ? ? ? ? ? }
? ? ? ? }
AbstractApplicationContext.Close這個方法是要你自己調用的,在程序要結束的時候保證調用這個close方法,在這里的話就是由Listener來保證tomcat退出的時候調用close方法。
AbstractApplicationContext.Close的代碼 :
?
publicvoid close(){
? ? ? ? ? ? ? ? logger.info("Closing application context [" + getDisplayName() + "]");

? ? ? ? ? ? ? ? // Destroy all cached singletons in this context,
? ? ? ? ? ? ? ? // invoking DisposableBean.destroy and/or "destroy-method".
? ? ? ? ? ? ? ? getBeanFactory().destroySingletons();?
??????????????? // publish corresponding event
? ? ? ? ? ? ? ? publishEvent(new ContextClosedEvent(this));
? ? ? ? }

最終還是調用到了getBeanFactory().destroySingletons(); 看來,沒有容器,我們還是需要自己來搞定這個方法的調用的 !