【Spring实战】—— 4 Spring中bean的init和destroy方法讲解
本篇文章主要介绍了在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方法讲解的更多相关文章
- JavaEE开发之Spring中Bean的作用域、Init和Destroy方法以及Spring-EL表达式
上篇博客我们聊了<JavaEE开发之Spring中的依赖注入以及AOP>,本篇博客我们就来聊一下Spring框架中的Bean的作用域以及Bean的Init和Destroy方法,然后在聊一下 ...
- 【Spring实战】Spring注解配置工作原理源码解析
一.背景知识 在[Spring实战]Spring容器初始化完成后执行初始化数据方法一文中说要分析其实现原理,于是就从源码中寻找答案,看源码容易跑偏,因此应当有个主线,或者带着问题.目标去看,这样才能最 ...
- 【Spring实战】Spring容器初始化完成后执行初始化数据方法
一.背景知识及需求 在做WEB项目时,经常在项目第一次启动时利用WEB容器的监听.Servlet加载初始化等切入点为数据库准备数据,这些初始化数据是系统开始运行前必须的数据,例如权限组.系统选项.默认 ...
- 【转】【Spring实战】Spring注解配置工作原理源码解析
一.背景知识 在[Spring实战]Spring容器初始化完成后执行初始化数据方法一文中说要分析其实现原理,于是就从源码中寻找答案,看源码容易跑偏,因此应当有个主线,或者带着问题.目标去看,这样才能最 ...
- Spring Bean的生命周期,《Spring 实战》书中的官方说法
连着两天的面试 ,都问到了 Spring 的Bean的生命周期,其中还包括 昨晚一波阿里的电话面试.这里找到了Spring 实战中的官方说法.希望各位要面试的小伙伴记住,以后有可能,或者是有时间 去看 ...
- Spring学习-- IOC 容器中 bean 的生命周期
Spring IOC 容器可以管理 bean 的生命周期 , Spring 允许在 bean 声明周期的特定点执行定制的任务. Spring IOC 容器对 bean 的生命周期进行管理的过程: 通过 ...
- Spring重点—— IOC 容器中 Bean 的生命周期
一.理解 Bean 的生命周期,对学习 Spring 的整个运行流程有极大的帮助. 二.在 IOC 容器中,Bean 的生命周期由 Spring IOC 容器进行管理. 三.在没有添加后置处理器的情况 ...
- Spring实战3:装配bean的进阶知识
主要内容: Environments and profiles Conditional bean declaration 处理自动装配的歧义 bean的作用域 The Spring Expressio ...
- Spring实战2:装配bean—依赖注入的本质
主要内容 Spring的配置方法概览 自动装配bean 基于Java配置文件装配bean 控制bean的创建和销毁 任何一个成功的应用都是由多个为了实现某个业务目标而相互协作的组件构成的,这些组件必须 ...
随机推荐
- C++ 构造函数与默认构造函数
构造函数:C++用于构建类的新对象时需要调用的函数,该函数无返回类型!(注意:是“无”! 不是空!(void)). 默认构造函数:未提供显式初始值时,用来穿件对象的构造函数. 以上是二者的定义,但是单 ...
- asp.net mvc 静态化
静态化的基本理解就是,常用的资源以文本形式保存,客户端访问时无需经过程序处理,直接下载 但是不存在的文件需要经过程序处理,文件内容如果需要有更动或删除,则直接删除文件本身 1.IIS Express ...
- web 导出数据到 exls 中
// 文件下载:导出excel表 @RequestMapping(value = "/exportExcel", method = {RequestMethod.GET}) @Re ...
- maria(mysql)的主从复制
一.mariadb的基本操作 1.远程连接 mysql -uroot -p -h 127.0.0.1 mysql -uroot -p -h 192.168.226.128 2.赋予远程连接的权限 gr ...
- Python中.ini文件使用
.ini文件 一般用来配置常量或者数据库链接语句等,是纯文本格式,所以可以用纯文本编辑器来编辑其内容. ;文件格式如下 ;注释用分号开头,setion 节 [setion] key = value s ...
- Html练习 | 小影志首页练习
<!DOCTYPE html> <head> <title>小影志首页练习</title> <style> /*应用全页字体*/ .pg-f ...
- NPM, BOWER, GIT, AND BASH PROXY CONFIGURATIONS
Sources: http://digitaldrummerj.me/proxy-configurations/ When you are using npm, bower, and git behi ...
- bootstrap框架的使用
1.默认修改input输入框激活的颜色(充电桩) .form-control:focus, .ms-choice:focus, input[type=text]:focus, input[type=p ...
- 记自己的hexo个人博客
https://othercoding.github.io/
- 如何设计一个“高大上”的 logo
前不久,我们老大写的一篇博客< Coding,做一个有情怀的产品 >中有提到设计 Coding logo 的大致由来,今天我就设计 Coding 猴头的过程具体说说如何设计一个 logo. ...