Spring中的destroy-method方法
1. Bean标签的destroy-method方法
配置数据源的时候,会有一个destroy-method方法
<bean id = "dataSource" class = "org.apache.commons.dbcp.BasicDataSource" destroy-method="close"><property name="driverClassName" value="${jdbc.driver}"></property><property name="url" value="${jdbc.url}"></property><property name="username" value="${jdbc.username}"></property><property name="password" value="${jdbc.password}"></property><property name="maxActive" value="${maxActive}"></property><property name="maxWait" value="${maxWait}"></property><property name="maxIdle" value="30"></property><property name="initialSize" value="2"></property></bean>The name of the custom destroy method to invoke on bean factory shutdown. The method must have no arguments, but may throw any exception. Note: Only invoked on beans whose lifecycle is under the full control of the factory - which is always the case for singletons, but not guaranteed for any other scope.
<listener> <listener-class>org.springframework.web.context.ContextLoaderListener </listener-class></listener>
public class ContextLoaderListener extends ContextLoader implements ServletContextListener { //这个是web容器初始化调用的方法。 public void contextInitialized(ServletContextEvent event) {this.contextLoader = createContextLoader();if (this.contextLoader == null) {this.contextLoader = this;}this.contextLoader.initWebApplicationContext(event.getServletContext());} //这个是web容器销毁时调用的方法。 public void contextDestroyed(ServletContextEvent event) {if (this.contextLoader != null) {this.contextLoader.closeWebApplicationContext(event.getServletContext());}ContextCleanupListener.cleanupAttributes(event.getServletContext());}public void contextInitialized(ServletContextEvent event);public void contextDestroyed(ServletContextEvent event);
public void closeWebApplicationContext(ServletContext servletContext) {servletContext.log("Closing Spring root WebApplicationContext");try {if (this.context instanceof ConfigurableWebApplicationContext) {((ConfigurableWebApplicationContext) this.context).close();}}finally {ClassLoader ccl = Thread.currentThread().getContextClassLoader();if (ccl == ContextLoader.class.getClassLoader()) {currentContext = null;}else if (ccl != null) {currentContextPerThread.remove(ccl);}servletContext.removeAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);if (this.parentContextRef != null) {this.parentContextRef.release();}}}protected void destroyBeans() { getBeanFactory().destroySingletons();}public synchronized void close() throws SQLException { GenericObjectPool oldpool = connectionPool; connectionPool = null; dataSource = null; try { if (oldpool != null) { oldpool.close(); } } catch(SQLException e) { throw e; } catch(RuntimeException e) { throw e; } catch(Exception e) { throw new SQLNestedException("Cannot close connection pool", e); } }