spring bean 卸载
起因:

群里的一个朋友问到: 关于配置destory-method, springboot中 yml如何指定

首先介绍 bean卸载的三种形式

自定义destory-method
实现 org.springframework.beans.factory.DisposableBean 或者 java.lang.AutoCloseable
@Bean 注解时,自动推断. 存在close() 或者 shutdown() 就调用
接下来看一个简单的卸载bean的例子

简单卸载示例
bean实体

public class MyDispose implements Closeable {
@Override
public void close() throws IOException {
System.out.println("MyDispose 执行关闭");
}
}

applicationContext.xml

<bean name="disposeBean" class="com.aya.mapper.model.MyDispose">
</bean>

测试类

@Test
public void testApplicationContextGetBean() {
ClassPathXmlApplicationContext factory = new ClassPathXmlApplicationContext("applicationContext.xml");
factory.close();
}

控制台输出:MyDispose 执行关闭

源码分析
接下来逆向分析,找到spring是如何卸载bean的

逆向-close
在 MyDispose.close() 断点

顺着调用堆栈一层一层往上找,直到 destroySingleton 部分

org.springframework.beans.factory.support.DefaultSingletonBeanRegistry

public void destroySingleton(String beanName) {
// Remove a registered singleton of the given name, if any.
removeSingleton(beanName);

// Destroy the corresponding DisposableBean instance.
DisposableBean disposableBean;
synchronized (this.disposableBeans) {
//集合移除对象,返回被移除的对象
disposableBean = (DisposableBean) this.disposableBeans.remove(beanName);
}
// 卸载移除的对象
destroyBean(beanName, disposableBean);
}

得出结论: this.disposableBeans.put 的地方就是注册卸载bean的地方,那里一定有条件判断

逆向-引用搜索
找到 this.disposableBeans 的定义private final Map<String, Object> disposableBeans = new LinkedHashMap<>();

然后搜索 disposableBeans 的所有引用,找到disposableBeans.put 的代码区

public void registerDisposableBean(String beanName, DisposableBean bean) {
synchronized (this.disposableBeans) {
this.disposableBeans.put(beanName, bean);
}
}

接下来对 registerDisposableBean 断点,在按照同样的方式,栈针回溯

逆向-条件判断
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry

protected void registerDisposableBeanIfNecessary(String beanName, Object bean, RootBeanDefinition mbd) {
AccessControlContext acc = (System.getSecurityManager() != null ? getAccessControlContext() : null);
// bean的 scope!=prototype && 必须是销毁的bean
if (!mbd.isPrototype() && requiresDestruction(bean, mbd)) {
if (mbd.isSingleton()) {
// 将 beanName 添加到 this.disposableBeans
registerDisposableBean(beanName,
new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc));
}
else {
// A bean with a custom scope...
Scope scope = this.scopes.get(mbd.getScope());
if (scope == null) {
throw new IllegalStateException("No Scope registered for scope name '" + mbd.getScope() + "'");
}
scope.registerDestructionCallback(beanName,
new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc));
}
}
}

接下来跟踪条件判断requiresDestruction,分析卸载的源头

org.springframework.beans.factory.support.DefaultSingletonBeanRegistry

protected boolean requiresDestruction(@Nullable Object bean, RootBeanDefinition mbd) {

return (bean != null &&
(DisposableBeanAdapter.hasDestroyMethod(bean, mbd) || (hasDestructionAwareBeanPostProcessors() &&
DisposableBeanAdapter.hasApplicableProcessors(bean, getBeanPostProcessors()))));
}

分为3组条件
1. bean!=null
2. bean 有卸载方法
3. 有实现DestructionAwareBeanPostProcessor的bean 并且 方法DestructionAwareBeanPostProcessor.requiresDestruction(bean)的结果为true

bean的卸载方法
org.springframework.beans.factory.support.DisposableBeanAdapter

private static final String CLOSE_METHOD_NAME = "close";

private static final String SHUTDOWN_METHOD_NAME = "shutdown";

public static boolean hasDestroyMethod(Object bean, RootBeanDefinition beanDefinition) {
//实现 `org.springframework.beans.factory.DisposableBean` 或者 `java.lang.AutoCloseable`
if (bean instanceof DisposableBean || bean instanceof AutoCloseable) {
return true;
}
String destroyMethodName = beanDefinition.getDestroyMethodName();
//@Bean 定义的bean. BeanDefinition的 destoryMethodName=AbstractBeanDefinition.INFER_METHOD
if (AbstractBeanDefinition.INFER_METHOD.equals(destroyMethodName)) {

return (ClassUtils.hasMethod(bean.getClass(), CLOSE_METHOD_NAME) ||
ClassUtils.hasMethod(bean.getClass(), SHUTDOWN_METHOD_NAME));
}
//自定义destory-method
return StringUtils.hasLength(destroyMethodName);
}

这里就到我们的结论区了

实现 org.springframework.beans.factory.DisposableBean 或者 java.lang.AutoCloseable
@Bean 注解时,自动推断. 存在close() 或者 shutdown() 就调用
自定义destory-method
问题场景
org.apache.commons.dbcp.BasicDataSource 为什么在xml必须定义destory-method而yml不用呢?

xml里面, BeanDefinition的destoryMethodName属性默认为null.

yml里面, 通过@Bean定义的bean, BeanDefinition的destoryMethodName属性默认为(inferred).

也就是说xml必须手动指定, @Bean 就算没指定,也会推断有没有close()或者shutdown方法,有就调用

自动定义
关于springboot中自动定义 DataSource 的相关内容做一个简单的描述

存在 spring.datasource.type 时, 注册相关的Bean

@ConditionalOnMissingBean(DataSource.class)
@ConditionalOnProperty(name = "spring.datasource.type")
static class Generic {

@Bean
public DataSource dataSource(DataSourceProperties properties) {
return properties.initializeDataSourceBuilder().build();
}

}

【转】spring bean 卸载的更多相关文章

  1. Spring8:一些常用的Spring Bean扩展接口

    前言 Spring是一款非常强大的框架,可以说是几乎所有的企业级Java项目使用了Spring,而Bean又是Spring框架的核心. Spring框架运用了非常多的设计模式,从整体上看,它的设计严格 ...

  2. Spring Bean详细讲解

    什么是Bean? Spring Bean是被实例的,组装的及被Spring 容器管理的Java对象. Spring 容器会自动完成@bean对象的实例化. 创建应用对象之间的协作关系的行为称为:装配( ...

  3. Spring Bean的生命周期(非常详细)

    Spring作为当前Java最流行.最强大的轻量级框架,受到了程序员的热烈欢迎.准确的了解Spring Bean的生命周期是非常必要的.我们通常使用ApplicationContext作为Spring ...

  4. spring bean的生命周期

    掌握好spring bean的生命周期,对spring的扩展大有帮助.  spring bean的生命周期(推荐看)  spring bean的生命周期

  5. spring bean的重新加载

    架构体系 在谈spring bean的重新加载前,首先我们来看看spring ioc容器. spring ioc容器主要功能是完成对bean的创建.依赖注入和管理等功能,而这些功能的实现是有下面几个组 ...

  6. Spring Bean

    一.Spring的几大模块:Data access & Integration.Transcation.Instrumentation.Core Spring Container.Testin ...

  7. 【转】Spring bean处理——回调函数

    Spring bean处理——回调函数 Spring中定义了三个可以用来对Spring bean或生成bean的BeanFactory进行处理的接口,InitializingBean.BeanPost ...

  8. 在非spring组件中注入spring bean

    1.在spring中配置如下<context:spring-configured/>     <context:load-time-weaver aspectj-weaving=&q ...

  9. spring bean生命周期管理--转

    Life Cycle Management of a Spring Bean 原文地址:http://javabeat.net/life-cycle-management-of-a-spring-be ...

随机推荐

  1. Python微服务实践-集成Consul配置中心

    A litmus test for whether an app has all config correctly factored out of the code is whether the co ...

  2. 【神经网络与深度学习】【计算机视觉】YOLO2

    YOLO2 转自:https://zhuanlan.zhihu.com/p/25167153?refer=xiaoleimlnote 本文是对 YOLO9000: Better, Faster, St ...

  3. (转)JVM原理讲解和调优

    背景:jvm实际调优在面试时候经常被问到,所以有必要认真总结一番. 转自:JVM原理讲解和调优 四.JVM内存调优 首先需要注意的是在对JVM内存调优的时候不能只看操作系统级别Java进程所占用的内存 ...

  4. 逸鹏说道公众号福利:逆天常用的一些谷歌浏览器插件V1.3

    插件导出:http://www.cnblogs.com/dunitian/p/5426552.html 插件导入:https://www.cnblogs.com/dotnetcrazy/p/97537 ...

  5. svn客户端清空账号信息的两种方法

    1.直接删除配置 C:\Users\Administrator\AppData\Roaming\Subversion\auth 一般在这个文件夹下 2.svn的设置里清空

  6. LeetCode 566. 重塑矩阵(Reshape the Matrix)

    566. 重塑矩阵 566. Reshape the Matrix 题目描述 LeetCode LeetCode LeetCode566. Reshape the Matrix简单 Java 实现 c ...

  7. jQuery的基础总结

    **本篇只列出零碎的jQuery基础知识点,个人记录自己的学习进度,无序排列,谨慎查看.** 1.jQuery入口函数的四种写法2.jQuery与JS遍历数组的区别3.jQuery符号冲突问题4.jQ ...

  8. css中常用的选择器和选择器优先级

    css常用的选择器:类选择器,id选择器,元素选择器,伪类选择器,伪元素选择器,属性选择器. 选择器的优先级由四个部分组成:0,0,0,0 一个选择器的具体优先级如下规则确定: ID选择器 加 0,1 ...

  9. 爬虫请求库之requests库

    一.介绍 介绍:使用requests可以模拟浏览器的请求,比之前的urllib库使用更加方便 注意:requests库发送请求将网页内容下载下来之后,并不会执行js代码,这需要我们自己分析目标站点然后 ...

  10. epoll_ctl函数的使用

    #include <sys/epoll.h> int epoll_ctl(int epfd, int op, int fd, struct epoll_event *event);作用: ...