zoukankan      html  css  js  c++  java
  • Spring中的destroy-method方法

    1. Bean标签的destroy-method方法

    配置数据源的时候,会有一个destroy-method方法

    <bean id="userBean" class="com.spring.ioc.User" destroy-method="close">
    
        ......
    
    </bean>
    

      

    在bean工厂关闭时调用自定义销毁方法的名称.

    其实,这是依赖在Servlet容器或者EJB容器中,它才会被自动给调用的。比如我们用Servlet容器,经常在web.xml文件中配置这样的监听器

    <listener>
       <listener-class>
    	org.springframework.web.context.ContextLoaderListener
       </listener-class>
    </listener>
    

      我们按层次包,看一下ContextLoaderListener这个类。

    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();
    			}
    		}
    	}
    

      

    这里面,将context转型为ConfigurableWebApplicationContext,而
    ConfigurableWebApplicationContext继承自ConfigurableApplicationContext,在ConfigurableApplicationContext(ConfigurableApplicationContext实现了Lifecycle,正是前文提到的lifecycle)里有
    close()方法的定义。在AbstractApplicationContext实现了close()方法。真正执行的是

    protected void destroyBeans() {
        getBeanFactory().destroySingletons();
    }
    

      方法(spring容器在启动的时候,会创建org.apache.commons.dbcp.BasicDataSource的对象,放入singleton缓存中。那么在容器销毁的时候,会清空缓存并调用BasicDataSourc中的close()方法。
    )
    BasicDataSourc类中的close()方法

    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);
            }
        }
    

      那么,如果spring不在Servlet或者EJB容器中,我们就需要手动的调用AbstractApplicationContext类中的close()方法,去实现相应关闭的功能。

  • 相关阅读:
    【第五章】printf输出顺序
    【转载】面试_现在有4个石头,1000层的楼房,需要测定这个石头破碎的高度。求最少多少次一定可以测出来。
    卷积和积分运算
    【转载】SIFT算法分析(草稿)
    【第五章】指针类型转换
    【第八章】zigzag数组输出
    【转载】SURF算法源码分析(草稿)
    【第六章】const函数改变变量的值——mutable
    Surf算法
    jsp页面中文乱码总结
  • 原文地址:https://www.cnblogs.com/skyLogin/p/6571459.html
Copyright © 2011-2022 走看看