`

Spring中的destroy-method方法

 
阅读更多

转载:http://technoboy.iteye.com/blog/970293。destroy-method 欠缺,补上。

 

1. Bean标签的destroy-method方法

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

Java代码 复制代码 收藏代码
  1. <bean id = "dataSource" class = "org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
  2. <property name="driverClassName" value="${jdbc.driver}"></property>
  3. <property name="url" value="${jdbc.url}"></property>
  4. <property name="username" value="${jdbc.username}"></property>
  5. <property name="password" value="${jdbc.password}"></property>
  6. <property name="maxActive" value="${maxActive}"></property>
  7. <property name="maxWait" value="${maxWait}"></property>
  8. <property name="maxIdle" value="30"></property>
  9. <property name="initialSize" value="2"></property>
  10. </bean>
<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>

这个destroy-method属性是干什么用的。什么时候调用呢?
Spring中的doc上是这么说destroy-method方法的---
Java代码 复制代码 收藏代码
  1. 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.
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.

其实,这是依赖在Servlet容器或者EJB容器中,它才会被自动给调用的。比如我们用Servlet容器,经常在web.xml文件中配置这样的监听器
Java代码 复制代码 收藏代码
  1. <listener>
  2. <listener-class>
  3. org.springframework.web.context.ContextLoaderListener
  4. </listener-class>
  5. </listener>
<listener>
   <listener-class>
	org.springframework.web.context.ContextLoaderListener
   </listener-class>
</listener>

我们按层次包,看一下ContextLoaderListener这个类。
Java代码 复制代码 收藏代码
  1. public class ContextLoaderListener extends ContextLoader implements ServletContextListener {
  2. //这个是web容器初始化调用的方法。
  3. public void contextInitialized(ServletContextEvent event) {
  4. this.contextLoader = createContextLoader();
  5. if (this.contextLoader == null) {
  6. this.contextLoader = this;
  7. }
  8. this.contextLoader.initWebApplicationContext(event.getServletContext());
  9. }
  10. //这个是web容器销毁时调用的方法。
  11. public void contextDestroyed(ServletContextEvent event) {
  12. if (this.contextLoader != null) {
  13. this.contextLoader.closeWebApplicationContext(event.getServletContext());
  14. }
  15. ContextCleanupListener.cleanupAttributes(event.getServletContext());
  16. }
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());
	}

ContextLoaderListener实现了javax.servlet.ServletContextListener,它是servlet容器的监听器接口。
ServletContextListener接口中定义了两个方法。
Java代码 复制代码 收藏代码
  1. public void contextInitialized(ServletContextEvent event);
  2. public void contextDestroyed(ServletContextEvent event);
public void contextInitialized(ServletContextEvent event);
public void contextDestroyed(ServletContextEvent event);

分别在容器初始化或者销毁的时候调用。
那么当我们销毁容器的时候,其实就是调用的contextDestroyed方法里面的内容。
这里面执行了ContextLoader的closeWebApplicationContext方法。
Java代码 复制代码 收藏代码
  1. public void closeWebApplicationContext(ServletContext servletContext) {
  2. servletContext.log("Closing Spring root WebApplicationContext");
  3. try {
  4. if (this.context instanceof ConfigurableWebApplicationContext) {
  5. ((ConfigurableWebApplicationContext) this.context).close();
  6. }
  7. }
  8. finally {
  9. ClassLoader ccl = Thread.currentThread().getContextClassLoader();
  10. if (ccl == ContextLoader.class.getClassLoader()) {
  11. currentContext = null;
  12. }
  13. else if (ccl != null) {
  14. currentContextPerThread.remove(ccl);
  15. }
  16. servletContext.removeAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
  17. if (this.parentContextRef != null) {
  18. this.parentContextRef.release();
  19. }
  20. }
  21. }
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()方法。真正执行的是
Java代码 复制代码 收藏代码
  1. protected void destroyBeans() {
  2. getBeanFactory().destroySingletons();
  3. }
protected void destroyBeans() {
    getBeanFactory().destroySingletons();
}

方法(spring容器在启动的时候,会创建org.apache.commons.dbcp.BasicDataSource的对象,放入singleton缓存中。那么在容器销毁的时候,会清空缓存并调用BasicDataSourc中的close()方法。
)
BasicDataSourc类中的close()方法
Java代码 复制代码 收藏代码
  1. public synchronized void close() throws SQLException {
  2. GenericObjectPool oldpool = connectionPool;
  3. connectionPool = null;
  4. dataSource = null;
  5. try {
  6. if (oldpool != null) {
  7. oldpool.close();
  8. }
  9. } catch(SQLException e) {
  10. throw e;
  11. } catch(RuntimeException e) {
  12. throw e;
  13. } catch(Exception e) {
  14. throw new SQLNestedException("Cannot close connection pool", e);
  15. }
  16. }
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()方法,去实现相应关闭的功能。

 

 

分享到:
评论
1 楼 xuezhongyu01 2017-12-19  
博主写的很详细,但最后还是没明白,最后调用BasicDataSourc类中的close()方法的作用是什么

相关推荐

    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"&gt; &lt;value&gt;org.gjt.mm.mysql.Driver &lt;value&gt;jdbc:mysql://localhost:3306/demo &lt;value&gt;root &lt;value&gt;root &lt;/bean&gt;

    spring1.2学习心得分享

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

    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-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-xmemcached

    &lt;bean id="cachingClient" class="com.dmx.cache.caching.impl.CachingXMemcachedClient" init-method="init" destroy-method="destroy"&gt; ${XMemcached_isflushAll}" /&gt; ...

    spring1.1开发理解

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

    JTA事务源码示例

    &lt;bean id="dataSourceA" class="org.enhydra.jdbc.pool.StandardXAPoolDataSource" destroy-method="shutdown"&gt; &lt;bean class="org.enhydra.jdbc.standard.StandardXADataSource" destroy-method="shutdown"&gt; ...

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

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

    springjdbc

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

    spring学习心得

    资源释放:&lt;bean destroy-method=""/&gt;仅对单例对象有效 (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 .........................................................

    Spring.html

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

    Spring的学习笔记

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

    spring applicationContext 配置文件

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

    JSP Spring中Druid连接池配置详解

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

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

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

    07-IoC配置-scope属性

    scope属性 名称: scope类型:属性 归属: bean标签 作用:定义bean的作用范围 格式: “singleton"&gt; ...singleton:设定创建出的对象保存在spring容器中,是一个单例的对象(bean默认是...名称: init-method, destroy-metho

Global site tag (gtag.js) - Google Analytics