【spring源码系列】之【Bean的销毁】

以“冬奥之光,多彩冰灯”为主题的第四十一届全国专业冰雕比赛在冰城哈尔滨市进入第二天,60名冰雕高手在哈尔滨冰灯艺术游园会园区展开激烈的竞技比拼。
冰雕艺术
1. 概述
Bean的销毁是Bean的生命周期中最后一步,比如在Tomcat等容器关闭的时候会调用Bean的销毁方法,下面逐步分析。
2. 源码分析
在bean创建完成后,就会对这个bean注册一个销毁的Adapter对象,
protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
throws BeanCreationException {
......
if (instanceWrapper == null) {
//创建对象实例
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
Object bean = instanceWrapper.getWrappedInstance();
Class<?> beanType = instanceWrapper.getWrappedClass();
if (beanType != NullBean.class) {
mbd.resolvedTargetType = beanType;
}
......
try {
// 属性赋值
populateBean(beanName, mbd, instanceWrapper);
// 初始化bean
exposedObject = initializeBean(beanName, exposedObject, mbd);
}
catch (Throwable ex) {
if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
throw (BeanCreationException) ex;
}
else {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
}
}
......
// Register bean as disposable.
try {
// 注册销毁的bean
registerDisposableBeanIfNecessary(beanName, bean, mbd);
}
catch (BeanDefinitionValidationException ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
}
return exposedObject;
}
registerDisposableBeanIfNecessary方法中disposableBeans集合负责收集需要销毁的bean。
protected void registerDisposableBeanIfNecessary(String beanName, Object bean, RootBeanDefinition mbd) {
AccessControlContext acc = (System.getSecurityManager() != null ? getAccessControlContext() : null);
if (!mbd.isPrototype() && requiresDestruction(bean, mbd)) {
if (mbd.isSingleton()) {
// Register a DisposableBean implementation that performs all destruction
// work for the given bean: DestructionAwareBeanPostProcessors,
// DisposableBean interface, custom destroy method.
// 注册销毁bean的DisposableBeanAdapter对象
registerDisposableBean(beanName,
new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc));
}
......
public void registerDisposableBean(String beanName, DisposableBean bean) {
synchronized (this.disposableBeans) {
this.disposableBeans.put(beanName, bean);
}
}
DisposableBeanAdapter 对象就是负责 bean 销毁的类,这个类中收集 bean是否实现了 DisposableBean 接口
class DisposableBeanAdapter implements DisposableBean, Runnable, Serializable
是否配置 destroy-method 属性,过滤了 DestructionAwareBeanPostProcessor 类型的接口,如下图所示:
public DisposableBeanAdapter(Object bean, String beanName, RootBeanDefinition beanDefinition,
List<BeanPostProcessor> postProcessors, @Nullable AccessControlContext acc) {
......
this.beanPostProcessors = filterPostProcessors(postProcessors, bean);
}
private List<DestructionAwareBeanPostProcessor> filterPostProcessors(List<BeanPostProcessor> processors, Object bean) {
List<DestructionAwareBeanPostProcessor> filteredPostProcessors = null;
if (!CollectionUtils.isEmpty(processors)) {
filteredPostProcessors = new ArrayList<>(processors.size());
for (BeanPostProcessor processor : processors) {
if (processor instanceof DestructionAwareBeanPostProcessor) {
DestructionAwareBeanPostProcessor dabpp = (DestructionAwareBeanPostProcessor) processor;
if (dabpp.requiresDestruction(bean)) {
filteredPostProcessors.add(dabpp);
}
}
}
}
return filteredPostProcessors;
然后 bean 是在什么时候被销毁呢,在 tomcat 关闭的时候就会调用到 servlet 中的销毁方法,具体是通过类ContextLoaderListener.java 中的contextDestroyed 方法,通过 closeWebApplicationContext 方法一直往下找此为 servlet 规范的使用,一路往下调用。








最终会进入DisposableBeanAdapter类中的destroy,方法该方法就会根据前面的收集进行调用。
public void destroy() {
// 处理@PreDestroy注解的beanpostProcessor实现类: InitDestroyAnnotationBeanPostProcessor
if (!CollectionUtils.isEmpty(this.beanPostProcessors)) {
for (DestructionAwareBeanPostProcessor processor : this.beanPostProcessors) {
processor.postProcessBeforeDestruction(this.bean, this.beanName);
}
}
// 处理实现DisposableBean接口的bean的销毁
if (this.invokeDisposableBean) {
if (logger.isTraceEnabled()) {
logger.trace("Invoking destroy() on bean with name '" + this.beanName + "'");
}
try {
if (System.getSecurityManager() != null) {
AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () -> {
((DisposableBean) this.bean).destroy();
return null;
}, this.acc);
}
else {
((DisposableBean) this.bean).destroy();
}
}
catch (Throwable ex) {
String msg = "Invocation of destroy method failed on bean with name '" + this.beanName + "'";
if (logger.isDebugEnabled()) {
logger.warn(msg, ex);
}
else {
logger.warn(msg + ": " + ex);
}
}
}
// 处理在配置文件中的bean配置了destroy-method的bean的销毁
if (this.destroyMethod != null) {
invokeCustomDestroyMethod(this.destroyMethod);
}
else if (this.destroyMethodName != null) {
Method methodToInvoke = determineDestroyMethod(this.destroyMethodName);
if (methodToInvoke != null) {
invokeCustomDestroyMethod(ClassUtils.getInterfaceMethodIfPossible(methodToInvoke));
}
}
}
销毁bean的顺序是如下:
1)判断是否需要处理@PreDestroy注解的bean,如果需要,则通过beanpostProcessor实现类 InitDestroyAnnotationBeanPostProcessor处理;
2)判断是否需要处理实现DisposableBean接口的bean的销毁;
3)判断是否需要处理配置文件中的bean配置了destroy-method的bean的销毁。
3. 案例演示
定义Bean,同时加入销毁对应的三种方法;
/**
* @Author: wzj
* @Date: 2021/7/2 11:32
* @Desc:
*/
public class Wzj implements DisposableBean {
public static Wzj factoryMethod() {
CQ cq = new CQ();
SC sc = new SC();
return new Wzj(sc, cq);
}
@PreDestroy
public void close() {
System.out.println("通过 @PreDestroy:销毁实例wzj");
}
public void destroyMethod() {
System.out.println("通过配置文件配置destroy-method:销毁实例wzj");
}
@Override
public void destroy() {
System.out.println("通过DisposableBean接口:销毁实例wzj");
}
配置文件如下:
<bean id="wzj" class="com.wzj.bean.Wzj" factory-method="factoryMethod" destroy-method="destroyMethod"/>
测试类:
/**
* @Author: wzj
* @Date: 2021/3/30 15:08
* @Desc: 测试类
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:spring.xml"})
public class TestSpring {
@Autowired
private ApplicationContext applicationContext;
@Test
public void testDestroy() {
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
Wzj wzj = (Wzj)applicationContext.getBean("wzj");
applicationContext.getBeanFactory().destroyBean("wzj");
}
结果:

有人可能会问,为何Bean可以多次销毁,其实Bean的销毁并不是真正意义上的销毁Bean,而是在销毁前执行销毁方法,可能包含关闭数据库连接、关闭网络请求等逻辑操作,而后真正的销毁是由Spring容器执行关闭,其内部Bean也就自然而然消失了,Bean销毁是发生在Spring容器关闭过程中的。
【spring源码系列】之【Bean的销毁】的更多相关文章
- Spring源码系列(二)--bean组件的源码分析
简介 spring-bean 组件是 Spring IoC 的核心,我们可以使用它的 beanFactory 来获取所需的对象,对象的实例化.属性装配和初始化等都可以交给 spring 来管理. 本文 ...
- Spring源码系列(三)--spring-aop的基础组件、架构和使用
简介 前面已经讲完 spring-bean( 详见Spring ),这篇博客开始攻克 Spring 的另一个重要模块--spring-aop. spring-aop 可以实现动态代理(底层是使用 JD ...
- Spring源码系列(四)--spring-aop是如何设计的
简介 spring-aop 用于生成动态代理类(底层是使用 JDK 动态代理或 cglib 来生成代理类),搭配 spring-bean 一起使用,可以使 AOP 更加解耦.方便.在实际项目中,spr ...
- Spring源码系列 — Bean生命周期
前言 上篇文章中介绍了Spring容器的扩展点,这个是在Bean的创建过程之前执行的逻辑.承接扩展点之后,就是Spring容器的另一个核心:Bean的生命周期过程.这个生命周期过程大致经历了一下的几个 ...
- Spring源码系列 — 注解原理
前言 前文中主要介绍了Spring中处理BeanDefinition的扩展点,其中着重介绍BeanDefinitionParser方式的扩展.本篇文章承接该内容,详解Spring中如何利用BeanDe ...
- Spring源码系列 — BeanDefinition
一.前言 回顾 在Spring源码系列第二篇中介绍了Environment组件,后续又介绍Spring中Resource的抽象,但是对于上下文的启动过程详解并未继续.经过一个星期的准备,梳理了Spri ...
- Spring源码分析之Bean的创建过程详解
前文传送门: Spring源码分析之预启动流程 Spring源码分析之BeanFactory体系结构 Spring源码分析之BeanFactoryPostProcessor调用过程详解 本文内容: 在 ...
- 事件机制-Spring 源码系列(4)
事件机制-Spring 源码系列(4) 目录: Ioc容器beanDefinition-Spring 源码(1) Ioc容器依赖注入-Spring 源码(2) Ioc容器BeanPostProcess ...
- Ioc容器依赖注入-Spring 源码系列(2)
Ioc容器依赖注入-Spring 源码系列(2) 目录: Ioc容器beanDefinition-Spring 源码(1) Ioc容器依赖注入-Spring 源码(2) Ioc容器BeanPostPr ...
- Ioc容器BeanPostProcessor-Spring 源码系列(3)
Ioc容器BeanPostProcessor-Spring 源码系列(3) 目录: Ioc容器beanDefinition-Spring 源码(1) Ioc容器依赖注入-Spring 源码(2) Io ...
随机推荐
- docker 安装遇到404 not find
https://mirrors.ustc.edu.cn/docker-ce/linux/centos/docker-ce/repodata/repomd.xml: [Errno 14] HTTPS E ...
- UCB DS100 讲义《数据科学的原理与技巧》校对活动正式启动 | ApacheCN
贡献指南:https://github.com/apachecn/ds100-textbook-zh/blob/master/CONTRIBUTING.md 整体进度:https://github.c ...
- 21个实用便利的PHP代码
转载请注明来源:https://www.cnblogs.com/hookjc/ 1. PHP可阅读随机字符串 此代码将创建一个可阅读的字符串,使其更接近词典中的单词,实用且具有密码验证功能. /*** ...
- 关于viewControllers之间的传值方式
AViewController----Push----BViewController 1.属性 AViewController---pop----BViewController 1.代理 2.通知 ...
- c++类模板与其他
static static的成员不再单独属于一个对象,他是单独的保存在内存的某个地址,也就只有一份.所以在设计程序的时候要看这个东西是不是只需要一份. static函数和一般的函数一样,在内存中只有一 ...
- MySQL语法命令之约束篇
文章目录 1.约束概述 1.1约束的分类 1.2添加约束 2.查看表中的约束 3. `not null` 非空约束 3.1 在 `create table` 时创建 3.2 在`alter table ...
- 1day漏洞反推技巧实战(3)
代码审计必备技能,github代码对比,写一笔: 搜索某开源组建漏洞,搜索出来某个版本rce: 通过消息得出:存在漏洞版本:1.10.10 ,修复漏洞版本1.10.11 去github寻找apache ...
- 帆软报表(finereport)JS实现长页面锚点定位
在报表的应用需求中,页面过长时,需要页面中实现类似HTML中锚点功能以跳转到相应需要预览模块 1实现思路 在设计器中所做的操作最终都会以HTML形式展现在网页.在这里我们为报表块单元格加上id选择器配 ...
- 从零开始, 开发一个 Web Office 套件 (3): 鼠标事件
这是一个系列博客, 最终目的是要做一个基于HTML Canvas 的, 类似于微软 Office 的 Web Office 套件, 包括: 文档, 表格, 幻灯片... 等等. 对应的Github r ...
- MyBatis加强(4)~mybatis 插件开发
一.插件介绍[动态代理] 1.插件[动态代理]:mybatis 允许在已经映射的语句的执行过程的某个时机进行拦截增强的机制. 2.mybatis中的组件动态代理的运用: MyBatis 在四大组件对象 ...