`
guoyiqi
  • 浏览: 967732 次
社区版块
存档分类
最新评论

Spring中的destroy-method

阅读更多
究竟Spring在何时调用destroy-method="close" 这个方法close()呢?终于借助JavaEye找到了答案,原来如果Spring不在Web Container或是EJB Container中的时候,这个方法还是需要我们自己来调用的,具体就是调用BeanFactory的destroySingletons()方法,文档上的“自动调用”这几个字真是害我不浅呀,原来自动也是通过Web Container或是EJB Container才可以自动,具体做法就是要实现ServletContextListener这个接口,Spring中已经有具体的实现了:
 
public class ContextLoaderListener implements ServletContextListener {

        private ContextLoader contextLoader;

        /**
        * Initialize the root web application context.
        */

        public void 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() {
                return new ContextLoader();
        }

        /**
        * Return the ContextLoader used by this listener.
        */

        public ContextLoader getContextLoader() {
                return contextLoader;
        }

        /**
        * Close the root web application context.
        */

        public void contextDestroyed(ServletContextEvent event) {
                this.contextLoader.closeWebApplicationContext(event.getServletContext());
        }

}
当tomcat关闭的时候会自动调用contextDestroyed(ServletContextEvent event)这个方法。在看一下contextLoader的closeWebApplicationContext方法:
 
public void 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的代码 :
 
public void 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(); 看来,没有容器,我们还是需要自己来搞定这个方法的调用的 !

- 作者: hpq852 2004年12月28日, 星期二 18:07

举个例子,ContextLoaderListener的源代码,
我们知道,如果要在tomcat里面使用spring的话需要这个Listener(或者ContextLoaderServlet)

代码
 public class ContextLoaderListener implements ServletContextListener {

 

private ContextLoader contextLoader;

/**
* Initialize the root web application context.
*
/
public void 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() {
return new ContextLoader();
}

/**
* Return the ContextLoader used by this listener.
*
/
public ContextLoader getContextLoader() {
return contextLoader;
}

/**
* Close the root web application context.
*
/
public void contextDestroyed(ServletContextEvent event) {
this.contextLoader.closeWebApplicationContext(event.getServletContext());
}

}


当tomcat关闭的时候会自动调用contextDestroyed(ServletContextEvent event)这个方法。在看一下contextLoader的closeWebApplicationContext方法:

代码
 	public void 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的代码

代码
 	public void 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));
}


其实就是调用context里面的beanFactory的destroySingletons()方法了,这个没什么好说的。我的意思就是,容器本身不知道什么时候要shutdown了,这个消息是要靠外部(程序员)来提供的。

 

de3light

分享到:
评论
1 楼 zhuixun_hebe 2008-12-22  
   [i][/i][u][/u]
引用
[img][/img][url][/url][flash=200,200][/flash]

相关推荐

    spring 配置文件简单说明

    2)default-destroy-method="方法名" 定义在此配置文件中的bean都会在执行指定的destroy方法。 3)default-lazy-init ="false|true" 定义在此配置文件中的bean都会延迟加载。 ....................

    08-IoC配置-bean的生命周期控制

    Spring IOC容器可以管理Bean的生命周期,允许在Bean生命周期的特定点执行定制的任务。 Spring IOC容器对Bean的生命周期...在 Bean 的声明里设置 init-method 和 destroy-method 属性, 为 Bean 指定初始化和销毁方法。

    spring Ioc容器配置

    spring Ioc容器配置 ... destroy-method="close"> <value>org.gjt.mm.mysql.Driver <value>jdbc:mysql://localhost:3306/demo <value>root <value>root </bean>

    spring1.2学习心得分享

    资源释放:<bean destroy-method=""/>仅对单例对象有效 (2)IoC概念 Inversion of Control 控制反转或控制转移 Don't Call Me,We will call you! 控制权:对象的创建和调用关系的控制. (3)DI概念 Dependecy ...

    spring-framework-reference-4.1.2

    3. New Features and Enhancements in Spring Framework 4.0 ............................................ 17 3.1. Improved Getting Started Experience .........................................................

    EWALectureNotes:幻灯片和讲座笔记Hacettepe大学的企业Web体系结构讲座的笔记

    EWA讲义 Hacettepe大学企业Web体系结构讲座的幻灯片和示例应用程序 应用清单: AjaxApp:基于Eclipse的Web项目,使用jQuery演示...spring-bean-lifecycle:使用init-method,destroy-method,InitializingBean,Disp

    Spring IOC Bean标签属性介绍(教学视频+源代码)

    Spring IOC Bean标签属性介绍 0.Bean标签属性介绍 1.0 新建一个Maven工程 1.1 pom.xml ...1.9 init-method和destroy-method 1.9.1 实体类JavaBean User加自定义的初始化方法和销毁方法 1.9.3 加了lazy

    spring-xmemcached

    <bean id="cachingClient" class="com.dmx.cache.caching.impl.CachingXMemcachedClient" init-method="init" destroy-method="destroy"> ${XMemcached_isflushAll}" /> ...

    spring1.1开发理解

    资源释放:<bean destroy-method=""/>仅对单例对象有效 (2)IoC概念 Inversion of Control 控制反转或控制转移 Don't Call Me,We will call you! 控制权:对象的创建和调用关系的控制. (3)DI概念 Dependecy ...

    JTA事务源码示例

    <bean id="dataSourceA" class="org.enhydra.jdbc.pool.StandardXAPoolDataSource" destroy-method="shutdown"> <bean class="org.enhydra.jdbc.standard.StandardXADataSource" destroy-method="shutdown"> ...

    spring学习心得

    资源释放:<bean destroy-method=""/>仅对单例对象有效 (2)IoC概念 Inversion of Control 控制反转或控制转移 Don't Call Me,We will call you! 控制权:对象的创建和调用关系的控制. (3)DI概念 Dependecy ...

    spring-framework-reference4.1.4

    3. New Features and Enhancements in Spring Framework 4.0 ............................................ 17 3.1. Improved Getting Started Experience .........................................................

    springjdbc

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> ...

    Spring框架中 @Autowired 和 @Resource 注解的区别

     为了定义一个 bean 的安装和卸载,我们可以使用 init-method 和 destroy-method 参数简单的声明一下 ,其中 init-method 属性指定了一个方法,该方法在 bean 的实例化阶段会立即被调用;同样地,destro

    Spring.html

    destroy-method API BeanFactory:使用这个工厂创建对象的方式都是懒加载,在调用的时候再创建 ClassPathXmlApplicationContext:使用这个工厂创建对象,他会根据scope智能判断是否懒加载,如果是单例则创建容器时...

    JSP Spring中Druid连接池配置详解

    JSP Spring中Druid连接池配置 jdbc.properties url=jdbc:postgresql://***.... <bean id=dataSource class=com.alibaba.druid.pool.DruidDataSource init-method=init destroy-method=close> <!-- 基本属性 url、u

    Spring的学习笔记

    (二) init-method destroy-method 不要和prototype一起用(了解) 15 第六课:annotation方式Spring 16 一、 开始使用annotation配置Spring 16 二、 @Autowired、@Qualifier 16 (一) @Autowired 16 (二) @Qualifier ...

    Spring3中配置DBCP,C3P0,Proxool,Bonecp数据源

    <bean id="dataSource" class="org.logicalcobwebs.proxool.ProxoolDataSource" destroy-method="close"> <value>org.gjt.mm.mysql.Driver <value>jdbc:mysql://localhost/manytomany?useUnicode=true&...

    spring applicationContext 配置文件

    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> <property name="driverClass" value="oracle.jdbc.driver.OracleDriver"/> ...

Global site tag (gtag.js) - Google Analytics