Spring-Bean的销毁

news/2024/11/20 19:30:50/

Bean的销毁

public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {/*** Add the given bean to the list of disposable beans in this factory,* registering its DisposableBean interface and/or the given destroy method* to be called on factory shutdown (if applicable). Only applies to singletons.* @param beanName the name of the bean* @param bean the bean instance* @param mbd the bean definition for the bean* @see RootBeanDefinition#isSingleton* @see RootBeanDefinition#getDependsOn* @see #registerDisposableBean* @see #registerDependentBean*/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就是这里存进Map中的registerDisposableBean(beanName, new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessorCache().destructionAware, 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, getBeanPostProcessorCache().destructionAware, acc));}}}/*** Determine whether the given bean requires destruction on shutdown.* <p>The default implementation checks the DisposableBean interface as well as* a specified destroy method and registered DestructionAwareBeanPostProcessors.* @param bean the bean instance to check* @param mbd the corresponding bean definition* @see org.springframework.beans.factory.DisposableBean* @see AbstractBeanDefinition#getDestroyMethodName()* @see org.springframework.beans.factory.config.DestructionAwareBeanPostProcessor*/protected boolean requiresDestruction(Object bean, RootBeanDefinition mbd) {// 有没有销毁方法,有没有指定销毁方法return (bean.getClass() != NullBean.class && (DisposableBeanAdapter.hasDestroyMethod(bean, mbd) ||(hasDestructionAwareBeanPostProcessors() && DisposableBeanAdapter.hasApplicableProcessors(bean, getBeanPostProcessorCache().destructionAware))));}
}class DisposableBeanAdapter implements DisposableBean, Runnable, Serializable {/*** Check whether the given bean has any kind of destroy method to call.* @param bean the bean instance* @param beanDefinition the corresponding bean definition*/public static boolean hasDestroyMethod(Object bean, RootBeanDefinition beanDefinition) {// 实现接口DisposableBean或者AutoCloseable,有销毁的方法if (bean instanceof DisposableBean || bean instanceof AutoCloseable) {return true;}return inferDestroyMethodIfNecessary(bean, beanDefinition) != null;}/*** If the current value of the given beanDefinition's "destroyMethodName" property is* {@link AbstractBeanDefinition#INFER_METHOD}, then attempt to infer a destroy method.* Candidate methods are currently limited to public, no-arg methods named "close" or* "shutdown" (whether declared locally or inherited). The given BeanDefinition's* "destroyMethodName" is updated to be null if no such method is found, otherwise set* to the name of the inferred method. This constant serves as the default for the* {@code @Bean#destroyMethod} attribute and the value of the constant may also be* used in XML within the {@code <bean destroy-method="">} or {@code* <beans default-destroy-method="">} attributes.* <p>Also processes the {@link java.io.Closeable} and {@link java.lang.AutoCloseable}* interfaces, reflectively calling the "close" method on implementing beans as well.*/@Nullableprivate static String inferDestroyMethodIfNecessary(Object bean, RootBeanDefinition beanDefinition) {String destroyMethodName = beanDefinition.resolvedDestroyMethodName;if (destroyMethodName == null) {destroyMethodName = beanDefinition.getDestroyMethodName(); // INFER_METHOD = "(inferred)"; 特定情况使用类内部的close和shntdown方法if (AbstractBeanDefinition.INFER_METHOD.equals(destroyMethodName) ||(destroyMethodName == null && bean instanceof AutoCloseable)) {// Only perform destroy method inference or Closeable detection// in case of the bean not explicitly implementing DisposableBeandestroyMethodName = null;if (!(bean instanceof DisposableBean)) {try {destroyMethodName = bean.getClass().getMethod(CLOSE_METHOD_NAME).getName();}catch (NoSuchMethodException ex) {try {destroyMethodName = bean.getClass().getMethod(SHUTDOWN_METHOD_NAME).getName();}catch (NoSuchMethodException ex2) {// no candidate destroy method found}}}}beanDefinition.resolvedDestroyMethodName = (destroyMethodName != null ? destroyMethodName : "");}return (StringUtils.hasLength(destroyMethodName) ? destroyMethodName : null);}/*** Check whether the given bean has destruction-aware post-processors applying to it.* @param bean the bean instance* @param postProcessors the post-processor candidates*/public static boolean hasApplicableProcessors(Object bean, List<DestructionAwareBeanPostProcessor> postProcessors) {if (!CollectionUtils.isEmpty(postProcessors)) {for (DestructionAwareBeanPostProcessor processor : postProcessors) {if (processor.requiresDestruction(bean)) {return true;}}}return false;}
}

执行销毁的逻辑:

AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class);
// 方案一: 注册关闭钩子,进程正常关闭的时候会去调用销毁方法
applicationContext.registerShutdownHook();
// 方案二: 调用容器的close方法
applicationContext.close();/*** Register a shutdown hook {@linkplain Thread#getName() named}* {@code SpringContextShutdownHook} with the JVM runtime, closing this* context on JVM shutdown unless it has already been closed at that time.* <p>Delegates to {@code doClose()} for the actual closing procedure.* @see Runtime#addShutdownHook* @see ConfigurableApplicationContext#SHUTDOWN_HOOK_THREAD_NAME* @see #doClose()*/
@Override
public void registerShutdownHook() {if (this.shutdownHook == null) {// No shutdown hook registered yet.this.shutdownHook = new Thread(SHUTDOWN_HOOK_THREAD_NAME) {@Overridepublic void run() {synchronized (startupShutdownMonitor) {doClose();}}};Runtime.getRuntime().addShutdownHook(this.shutdownHook);}
}/*** Actually performs context closing: publishes a ContextClosedEvent and* destroys the singletons in the bean factory of this application context.* <p>Called by both {@code close()} and a JVM shutdown hook, if any.* @see org.springframework.context.event.ContextClosedEvent* @see #destroyBeans()* @see #close()* @see #registerShutdownHook()*/
@SuppressWarnings("deprecation")
protected void doClose() {// Check whether an actual close attempt is necessary...if (this.active.get() && this.closed.compareAndSet(false, true)) {if (logger.isDebugEnabled()) {logger.debug("Closing " + this);}if (!NativeDetector.inNativeImage()) {LiveBeansView.unregisterApplicationContext(this);}try {// Publish shutdown event.publishEvent(new ContextClosedEvent(this));}catch (Throwable ex) {logger.warn("Exception thrown from ApplicationListener handling ContextClosedEvent", ex);}// Stop all Lifecycle beans, to avoid delays during individual destruction.if (this.lifecycleProcessor != null) {try {this.lifecycleProcessor.onClose();}catch (Throwable ex) {logger.warn("Exception thrown from LifecycleProcessor on context close", ex);}}// Destroy all cached singletons in the context's BeanFactory.destroyBeans();// Close the state of this context itself.closeBeanFactory();// Let subclasses do some final clean-up if they wish...onClose();// Reset local application listeners to pre-refresh state.if (this.earlyApplicationListeners != null) {this.applicationListeners.clear();this.applicationListeners.addAll(this.earlyApplicationListeners);}// Switch to inactive.this.active.set(false);}
}

定义销毁逻辑:

// 方案一: 注册钩子或关闭容器执行销毁逻辑
@Component
public class UserService implements DisposableBean
{@Overridepublic void destroy() throws Exception {System.out.println(222);}
}// 方案二: 注册钩子或关闭容器执行销毁逻辑
@Component
public class UserService implements AutoCloseable
{@Overridepublic void close() throws Exception {System.out.println(333);}
}// 方案三: 注册钩子或关闭容器执行销毁逻辑
@Component
public class GaxBeanPostProcessor implements MergedBeanDefinitionPostProcessor
{@Overridepublic void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName){if ("userService".equals(beanName)){// 指定销毁方法的名字,固定字符串beanDefinition.setDestroyMethodName("(inferred)");}}
}@Component
public class UserService
{// 有close方法就执行close销毁public void close(){System.out.println(444);}// 没有close方法,再执行shutdown销毁public void shutdown(){System.out.println(555);}
}

总结BeanPostProcessor

1、InstantiationAwareBeanPostProcessor.postProcessBeforeInstantiation()

2、实例化

3、MergedBeanDefinitionPostProcessor.postProcessMergedBeanDefinition()

4、InstantiationAwareBeanPostProcessor.postProcessAfterInstantiation()

5、自动注入

6、InstantiationAwareBeanPostProcessor.postProcessProperties()

7、Aware对象

8、BeanPostProcessor.postProcessBeforeInitialization()

9、初始化

10、BeanPostProcessor.postProcessAfterInitialization()


http://www.ppmy.cn/news/1198001.html

相关文章

LV.12 D16 轮询与中断 学习笔记

一、CPU与硬件的交互方式 轮询 CPU执行程序时不断地询问硬件是否需要其服务&#xff0c;若需要则给予其服务&#xff0c;若不需要一段时间后再次询问&#xff0c;周而复始 中断 CPU执行程序时若硬件需要其服务&#xff0c;对应的硬件给CPU发送中断信号&#xff0c…

[算法日志]图论: 深度优先搜索(DFS)

[算法日志]图论&#xff1a; 深度优先搜索(DFS) 深度优先概论 ​ 深度优先搜索算法是一种遍历图这种数据结构的算法策略&#xff0c;其中心思想是朝图节点的一个方向不断跳转&#xff0c;当该节点无下一个节点或所有方向都遍历完时&#xff0c;便回溯朝上一个节点的另一个方向…

3、Sentinel 动态限流规则

Sentinel 的理念是开发者只需要关注资源的定义&#xff0c;当资源定义成功后可以动态增加各种流控降级规则。Sentinel 提供两种方式修改规则&#xff1a; • 通过 API 直接修改 (loadRules) • 通过 DataSource 适配不同数据源修改 通过 API 修改比较直观&#xff0c;可以通…

GEE数据集——原住民土地(原住民土地地图)数据集

原住民土地&#xff08;原住民土地地图&#xff09; 土地承认是人们在日常生活中融入原住民存在和土地权利意识的一种方式。这通常在仪式、讲座或教育指南开始时进行。它可以是一种明确但有限的方式来认识殖民主义和第一民族的历史以及定居者殖民社会变革的需要。在这种情况下…

十二星座这一辈子都在忙些什么 ?

白羊座&#xff08;着急)、金牛座&#xff08;在守候&#xff09;、双子座&#xff08;在徘徊&#xff09; 巨蟹座&#xff08;在等待&#xff09;、狮子座&#xff08;在控制&#xff09;、处女座&#xff08;在准备&#xff09; 天秤座&#xff08;在权衡&#xff09;、天蝎座…

使用udevdm查询蓝牙模块的信息

1.首先查询蓝牙设备在系统中的设备路径 udevadm info --querypath -n /dev/ttyS1 2.查询蓝牙设备的所有信息包括父设备信息 EMUELEC:~ # udevadm info -ap /devices/platform/ffd24000.serial/tty/ttyS1 备注&#xff1a;查询设备所有信息 udevadm info --queryall -n /dev…

静态、友好、内在:解析C++中的这些特殊元素和对象复制的优化

W...Y的主页 &#x1f60a; 代码仓库分享&#x1f495; &#x1f354;前言&#xff1a; 前面我们学习了C中关于类与对象的许多知识点&#xff0c;今天我们继续学习类与对象&#xff0c;最后再总结一下类与对象中的一些关键字内容&#xff0c;以及需要注意的细节。满满的干货…

财务RPA机器人如何使用

随着科技的不断发展&#xff0c;自动化技术在各个领域得到了广泛应用&#xff0c;在财务领域&#xff0c;RPA机器人已经成为一种新兴的技术手段&#xff0c;帮助众多企业实现了财务流程的自动化&#xff0c;大大提高了工作效率&#xff0c;降低人力成本。 本文将详细介绍财务RP…