本篇文章主要介绍了在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模式或者默认时,会得到如下的结果:

一月 ,  :: 下午 org.springframework.context.support.AbstractApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@4f5cb20e: startup date [Sun Jan :: CST ]; root of context hierarchy
一月 , :: 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [bean.xml]
一月 , :: 下午 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
演出开始前,开灯...
演出开始...
一月 , :: 下午 org.springframework.context.support.AbstractApplicationContext doClose
信息: Closing org.springframework.context.support.ClassPathXmlApplicationContext@4f5cb20e: startup date [Sun Jan :: CST ]; root of context hierarchy
一月 , :: 下午 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模式时,得到如下的结果:

一月 ,  :: 下午 org.springframework.context.support.AbstractApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@4eadddd6: startup date [Sun Jan :: CST ]; root of context hierarchy
一月 , :: 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [bean.xml]
一月 , :: 下午 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
演出开始前,开灯...
演出开始...
一月 , :: 下午 org.springframework.context.support.AbstractApplicationContext doClose
信息: Closing org.springframework.context.support.ClassPathXmlApplicationContext@4eadddd6: startup date [Sun Jan :: CST ]; root of context hierarchy
一月 , :: 下午 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

【Spring实战】—— 4 Spring中bean的init和destroy方法讲解的更多相关文章

  1. JavaEE开发之Spring中Bean的作用域、Init和Destroy方法以及Spring-EL表达式

    上篇博客我们聊了<JavaEE开发之Spring中的依赖注入以及AOP>,本篇博客我们就来聊一下Spring框架中的Bean的作用域以及Bean的Init和Destroy方法,然后在聊一下 ...

  2. 【Spring实战】Spring注解配置工作原理源码解析

    一.背景知识 在[Spring实战]Spring容器初始化完成后执行初始化数据方法一文中说要分析其实现原理,于是就从源码中寻找答案,看源码容易跑偏,因此应当有个主线,或者带着问题.目标去看,这样才能最 ...

  3. 【Spring实战】Spring容器初始化完成后执行初始化数据方法

    一.背景知识及需求 在做WEB项目时,经常在项目第一次启动时利用WEB容器的监听.Servlet加载初始化等切入点为数据库准备数据,这些初始化数据是系统开始运行前必须的数据,例如权限组.系统选项.默认 ...

  4. 【转】【Spring实战】Spring注解配置工作原理源码解析

    一.背景知识 在[Spring实战]Spring容器初始化完成后执行初始化数据方法一文中说要分析其实现原理,于是就从源码中寻找答案,看源码容易跑偏,因此应当有个主线,或者带着问题.目标去看,这样才能最 ...

  5. Spring Bean的生命周期,《Spring 实战》书中的官方说法

    连着两天的面试 ,都问到了 Spring 的Bean的生命周期,其中还包括 昨晚一波阿里的电话面试.这里找到了Spring 实战中的官方说法.希望各位要面试的小伙伴记住,以后有可能,或者是有时间 去看 ...

  6. Spring学习-- IOC 容器中 bean 的生命周期

    Spring IOC 容器可以管理 bean 的生命周期 , Spring 允许在 bean 声明周期的特定点执行定制的任务. Spring IOC 容器对 bean 的生命周期进行管理的过程: 通过 ...

  7. Spring重点—— IOC 容器中 Bean 的生命周期

    一.理解 Bean 的生命周期,对学习 Spring 的整个运行流程有极大的帮助. 二.在 IOC 容器中,Bean 的生命周期由 Spring IOC 容器进行管理. 三.在没有添加后置处理器的情况 ...

  8. Spring实战3:装配bean的进阶知识

    主要内容: Environments and profiles Conditional bean declaration 处理自动装配的歧义 bean的作用域 The Spring Expressio ...

  9. Spring实战2:装配bean—依赖注入的本质

    主要内容 Spring的配置方法概览 自动装配bean 基于Java配置文件装配bean 控制bean的创建和销毁 任何一个成功的应用都是由多个为了实现某个业务目标而相互协作的组件构成的,这些组件必须 ...

随机推荐

  1. 安装Linux虚拟机到执行Java程序

    1.安装VMware 2.在VMware里安装 CentOs 镜像(CentOS-7.2-x86_64-DVD-1511.iso) 3.启动CentOs后如果不能上网,或者 没有 ifconfig命令 ...

  2. redis源码搭建以及配置主从服务器

    2018-10-25 关闭防火墙: systemctl stop firewalld.service #停止firewall systemctl disable firewalld.service # ...

  3. PIE SDK栅格数据的金字塔创建

    1. 功能简介 金字塔可用于改善性能,可以加快栅格数据的显示速度.随着放大操作的进行,各个更精细的分辨率等级将逐渐得到绘制;但性能将保持不变:目前PIE SDK支持栅格数据的金字塔创建,下面对栅格数据 ...

  4. Thinkphp2.1漏洞利用

    thinkphp2.1版本 Google语法: inurl:index.php intext:ThinkPHP 2.1 { Fast & Simple OOP PHP Framework }  ...

  5. TimesTen LINUX 安装日志

    $ ./setup.sh NOTE: Each TimesTen installation is identified by a unique instance name. The instance ...

  6. Python+Selenium之HTMLTestRunner

    下载 HTMLTestRunner 模块 下载地址:http://tungwaiyip.info/software/HTMLTestRunner.html 保存路径:将下载的HTMLTestRunne ...

  7. linux 入门命令总结

    1,tree -d /etc/ 参数表示只显示目录 -f 显示内容的完整 -i 不显示树枝显示完整路径2,mkdir -p 递归创建多级目录 -v 显示创建目录的过程 -m 设置目录的默认权限 mkd ...

  8. async/await 的一些知识 (死锁问题)

    博文 Don't Block on Async Code What is the purpose of "return await" in C#? Any difference b ...

  9. sql server 远程备份 bak 删除

    前言: 管理一个公司的一个服务器,最近有一些维护SQLserver数据库活弄,写下防止忘了. 因为公司采用SQL\Redis\MongoDB共用,SQL用来存储基础的结构\权限\等一些杂七杂八的东西. ...

  10. JQuery脚本-通过禁用按钮防止表单重复提交

    <script type="text/javascript"> /* jquer 脚本,避免重复提交 隐藏点击的submit,后在他之后插入同名button伪装成被隐藏 ...