【Spring实战】—— 4 Spring中bean的init和destroy方法讲解

时间:2022-04-22
本文章向大家介绍【Spring实战】—— 4 Spring中bean的init和destroy方法讲解,主要内容包括singleton,也就是单例、prototype,原型、下面做个小例子,做一下验证:、参考、基本概念、基础应用、原理机制和需要注意的事项等,并结合实例形式分析了其使用技巧,希望通过本文能帮助到大家理解应用这部分内容。

本篇文章主要介绍了在spring中通过配置init-method和destroy-method方法来实现Bean的初始化和销毁时附加的操作。 在java中,我们并不需要去管理内存或者变量,而在C或C++中,可以通过new和delete等方式来创建和删除变量或者对象。在Spring中,如果想要对一个bean进行初始化和结束附加一定的操作,则可以使用上述的两个方法来实现。

  在介绍这两个方法前,读者需要了解Spring中bean的生命周期,最常使用的两种生命周期是:singleton和prototype。

  singleton,也就是单例

  在一个应用上下文容器中,所有的线程或对象通过getBean获得指定id的Bean,得到的都是同一个实例。

  这种的Bean实例完全由应用上下文容器来控制声明周期,用户无论何时何地得到的实例都是同一个

  举个例子,钓鱼岛只有一个,日本说是他们的,中国说是中国的。虽然两方存在争议,都觉得自己有所有权,但是钓鱼岛只有一个,因此我们所说的钓鱼岛跟日本所说的钓鱼岛就是同一个岛:

  prototype,原型

  这种类型的Bean会在每一次都创建一个新的实例,而实例的生命周期仅仅由应用上下文控制其初始化和装配,一旦初始化成功,控制权就会交给用户

  常见的场景,例如车票或者电影票Bean实例,每次都应该是一个新的实例,因为一个票只归属于同一个人。

  通过上面对生命周期的讲解,可以了解到,我们在spring中使用init-method和destroy-method方法时,仅仅在默认情况即singleton模式下,destroy-method才会起作用。

  下面做个小例子,做一下验证:

  举个例子,一个舞台Bean,我们想在使用舞台前打开灯光,在舞台使用后关闭灯光再拆掉舞台。就可以通过init-method和destroy-method来指定方法。

package com.spring.test.initdesotry;

public class Stage {
    public void perform(){
        System.out.println("演出开始...");
    }
    public void turnOnLight(){
        System.out.println("演出开始前,开灯...");
    }
    public void turnOffLight(){
        System.out.println("演出结束前,关灯...");
    }
}

  配置bean.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://www.springframework.org/schema/beans"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">    
     <bean id="stage" class="com.spring.test.initdesotry.Stage"
         scope="prototype" //注意这句话,如果是singleton或者没有该句(默认情况)时,才会执行destroy-method指定的方法,如果是当前的prototype不会触发destroymethod的执行
         init-method="turnOnLight" 
         destroy-method="turnOffLight"/>
</beans>

  在主函数中,不要忘记应用上下文容器的关闭,只有这样,才会出发destroy-method的执行。

package com.spring.test.initdesotry;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class test {
    public static void main(String[] args) {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("bean.xml");
        Stage stage = (Stage)ctx.getBean("stage");
        stage.perform();
        ((ClassPathXmlApplicationContext) ctx).close();//关闭应用上下文容器,不要忘记这句话
    }
}

  当Bean是singleton模式或者默认时,会得到如下的结果:

一月 25, 2015 1:30:42 下午 org.springframework.context.support.AbstractApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@4f5cb20e: startup date [Sun Jan 25 13:30:42 CST 2015]; root of context hierarchy
一月 25, 2015 1:30:42 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [bean.xml]
一月 25, 2015 1:30:42 下午 org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
信息: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@68df6513: defining beans [duke,sonnet29,poeticDuke,theStage,stage]; root of factory hierarchy
演出开始前,开灯...
演出开始...
一月 25, 2015 1:30:42 下午 org.springframework.context.support.AbstractApplicationContext doClose
信息: Closing org.springframework.context.support.ClassPathXmlApplicationContext@4f5cb20e: startup date [Sun Jan 25 13:30:42 CST 2015]; root of context hierarchy
一月 25, 2015 1:30:42 下午 org.springframework.beans.factory.support.DefaultSingletonBeanRegistry destroySingletons
信息: Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@68df6513: defining beans [duke,sonnet29,poeticDuke,theStage,stage]; root of factory hierarchy
演出结束前,关灯...

  当是prototype模式时,得到如下的结果:

一月 25, 2015 1:05:40 下午 org.springframework.context.support.AbstractApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@4eadddd6: startup date [Sun Jan 25 13:05:40 CST 2015]; root of context hierarchy
一月 25, 2015 1:05:40 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [bean.xml]
一月 25, 2015 1:05:40 下午 org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
信息: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@2264f82f: defining beans [duke,sonnet29,poeticDuke,theStage,stage]; root of factory hierarchy
演出开始前,开灯...
演出开始...
一月 25, 2015 1:05:40 下午 org.springframework.context.support.AbstractApplicationContext doClose
信息: Closing org.springframework.context.support.ClassPathXmlApplicationContext@4eadddd6: startup date [Sun Jan 25 13:05:40 CST 2015]; root of context hierarchy
一月 25, 2015 1:05:40 下午 org.springframework.beans.factory.support.DefaultSingletonBeanRegistry destroySingletons
信息: Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@2264f82f: defining beans [duke,sonnet29,poeticDuke,theStage,stage]; root of factory hierarchy

  参考

  1 《Spring in Action》

  2 Spring 中 init-method和destroy-method