Spring: 使用关闭钩子销毁bean

Spring中shutdown hook作用 阅读详情

Spring中关于bean的销毁有三种方法。分别是

1)执行某一方法如destroy()方法,然后在<bean>标签上的destroy-method属性制定方法名就行了。

2)实现DisopableBean接口的destroy方法,DispoableBean接口只有一个destroy方法,在bean销毁前调用。代码如下:

[java]  view plain  copy
 print ?
  1. public class DestructiveBeanImpl implements DisposableBean{  
  2.         public void destroy(){  
  3.             //System.out.println("销毁bean");//计入日志等代码  
  4.         }  
  5. }  

3)使用关闭钩子shutdownHook来进行销毁Bean。

Spring销毁回调的唯一确定是他们不能被自动触发,要记得在应用关闭之前调用

ConfigurableListableBeanFactory:destroySingletons()方法,

或者AbstractApplicationContext.registerShutdownHook()。


在java中允许创建一个关闭钩子,他是一个刚好在应用关闭前会被执行的一个线程。这是一个调用BeanFactory的destroySingletons方法的最佳途径。最简单的方法就是创建一个实现了Runnable接口的类,并在run()方法中调用destroySingletons()。代码清单如下:

[java]  view plain  copy
 print ?
  1. public class ShutdownHook implements Runnable{  
  2.         private ConfigurableListableBeanFactory beanfactory;  
  3.         public ShudownHook(ConfigurableListableBeanFactory beanfactory){  
  4.             Assert.notNull(beanfactroy, "The 'beanfactory' argument must not be null." );  
  5.             this.beanfactory = beanfactory;  
  6.         }  
  7.         public void run(){  //重写Runnable中的run方法并在此销毁bean  
  8.             this.beanfactory.destroySingletons();  
  9.         }  
  10. }  

注册关闭钩子代码如下:

[java]  view plain  copy
 print ?
  1. public class ShtdownHookDemo {  
  2.         public static void main(String[] args) throws IOException {  
  3.             XmlBeanFactory factory = new XmlBeanFactory( new ClassPathResource( "/META-INF/spring/lifecycle-context.xml"));  
  4.             Runtime.getRuntime().addShutdownHook( nwe Thread( new ShutdownHook(factory)));  //得到Runtime的引用并注册关闭钩子  
  5.             new BufferendInputStream(System.in).read();  
  6.         }  
  7. }  
Spring源码之bean的销毁registerDisposableBeanIfNecessary方法解读 目录前言`registerDisposableBeanIfNecessary()` 方法概览 前言 这篇文章是 IOC 容器初始化启动时,抽象类 AbstractAutowireCapableBeanFactory 的 doCreateBean() 方法里面的 registerDisposableBeanIfNecessary() 方法,它是进行 bean 的销毁的方法 阅读本篇文章,同时可以参考阅读 spring源码之getBean(获取 bean)方法解读(二) 和 spring aop代理对象的产生 阅读详情

相关推荐

7、Spring Bean 的初始化与销毁机制

XML 配置方式:在spring.xml配置文件中,可以通过和属性为 Bean 指定初始化和销毁的方法。这些方法将在 Bean 实例化后和销毁前通过反射机制进行调用。接口实现方式:实现接口的方法和接口的destroy()方法,来处理 Bean 的初始化和销毁逻辑。这种方式相对更符合面向对象设计思想,同时也提供了更细粒度的控制。通过以上实现,我们能够看到 Spring 框架对 Bean 的生命周期管理提供了灵活且强大的支持。

qq_29434541的博客 997

Spring学习之使用关闭钩子销毁bean

Spring中关于bean的销毁有三种方法。分别是1)执行某一方法如destroy()方法,然后在标签上的destroy-method属性制定方法名就行了。2)实现DisopableBean接口的destroy方法,DispoableBean接口只有一个destroy方法,在bean销毁前调用。代码如下: public class DestructiveBeanImpl implements

逆风奔跑。。不要去考虑什么天赋异禀,一切都来自经历和渴望。 1万+

第 08 章:龙行有风,向虚拟机注册钩子,实现Bean对象的初始化和销毁方法

作者:小傅哥 博客:https://bugstack.cn 沉淀、分享、成长,让自己和他人都能有所收获!???? 一、前言 有什么方式,能给代码留条活路? 有人说:人人都是产品经理,那你知道吗,人人也都可以是码农程序员!就像: 编程就是;定义属性、创建方法、调用展示 Java 和 PHP 就像男人和女人,前者在乎架构化模块后,后者在乎那个颜色我喜欢 用心写,但不要不做格式化 初次和产品对接的三个宝:砖头、铁锹、菜刀,分别保证有用、可用、好用 从一行代码到一吨代码,开发越来越难,壁垒也越来越高 其

bugstack虫洞栈 1777

Spring-Bean生命周期-注册容器关闭钩子

bean想要执行destroy方法,需要关闭容器。,close方法比较暴力,直接执行,代码顺序很重要,一般放在代码最后面。关闭容器,除了可以使用close方法,还可以注册容器关闭钩子。registerShutdownHook方法随便放哪都行。...

u011572366的博客 588

从零开始搭建GD32F103CBT6开发环境:VSCode配置与实战技巧

本文详细介绍了如何从零开始为国产MCU GD32F103CBT6搭建高效的VSCode开发环境。内容涵盖工具链安装、VSCode核心插件配置、工程目录结构规划、关键配置文件编写以及Makefile实战,旨在帮助开发者摆脱传统IDE束缚,利用现代化工具链提升嵌入式开发效率。

weixin_29158413的博客 448

带挂牵引车前向运动模型推导及仿真实现

牵引车-半挂车的车辆结构与普通的车辆相比增加了一个半挂车,它们之间通过鞍座相连接,为了分析半挂牵引车运动过程中的位姿和状态,本文将基于车辆的机械结构建立对应的运动学模型,该模型基于以下假设: 车辆行驶过程中,道路平坦且无凸凹; 车辆低速行驶,且运行过程中车身无侧倾和俯仰运动; 车辆行驶过程中,轮胎无形变,无侧向滑动,且无侧向力; 牵引车和半挂车均满足阿克曼转向几何原理; 牵引车与半挂车不会发现折叠。

jianmo的博客 3182

spring的钩子_Spring Boot关闭钩子

import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.EnableAutoConfiguration;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.s...

weixin_39987211的博客 735

MONAILabel in 3D Slicer 案例1: 在腹部CT中自动分割脾脏

MONAILabel in 3D Slicer 案例1: 在腹部CT中自动分割脾脏。

Tina姐的博客 1939

Springboot启动过程的源码

可能理解有误的可以指出来,仅仅只是源码查看分析,谢谢大家。 原理图:原理图是复制了其他人但是具体是哪个博主的忘记了。 1.SpringApplication 允许run之前的初始化三个步骤。 (1).通过org.springframework.web.context.ConfigurableWebApplicationContext既定的特征类判断applicationType是...

浪迹byb的博客 355

FDTD超表面仿真详细教程,几何相位,共振相位,传播相位

FDTD的超表面主要几何相位型(PB型)和共振型两种类型,其中PB型每个cell中的纳米棒的长宽相同,旋转角度不同,共振型长宽不同,旋转角度相同。本博文中以最常见的长方形纳米棒为例,用FDTD演示两种超表面实现的聚焦透镜的功能,包含详细步骤,其他形状,材料的超表面可自行尝试。

wuyuerhhg的博客 3万+

R语言中的Gamma分布函数

在R语言中,我们可以使用最大似然估计(Maximum Likelihood Estimation,MLE)或最小二乘估计(Least Squares Estimation,LSE)等方法来估计Gamma分布的参数。本文介绍了在R语言中使用Gamma分布函数的基本操作,包括生成随机变量、计算概率密度函数和累积分布函数,以及参数估计和拟合。函数来生成Gamma分布的随机变量,计算概率密度函数(PDF)和累积分布函数(CDF),以及进行参数估计和拟合。要计算Gamma分布的累积分布函数(CDF),我们可以使用。

ByteWhiz的博客 1632

高级Java开发者都知道的Hook钩子函数,你还不知道吗?

什么是钩子函数,在学习钩子函数之前,小编先提一个问题。 请问在Spring中,如果JVM异常终止,Spring是如何保证会释放掉占用的资源,比如说数据库连接等资源呢? 钩子函数非常简单,简单到小编只用摘抄一段Spring代码即可。走你,现在开始。 问题 Spring 容器中 Bean 在什么时候执行销毁方法? 我们知道在Spring中定义销毁方法有两种方式 实现 DisposableBean 的 destroy 方法。 使用 @PreDestroy 注解修饰方法 @Component public c.

西魏陶渊明的博客 3996

AutosarMCAL开发——基于EB MCU驱动

本文为博主个人学习总结记录,如有不正,欢迎指正。

qq_45583706的博客 922

Spring 容器的关闭流程

目录AbstractApplicationContext 中的相关源码关闭容器的2种方式核心方法 doClose()doClose() 流程图   AbstractApplicationContext 中的相关源码 关闭容器的2种方式 /** * 向jvm注册一个关闭钩子(shutdown hook),在jvm关闭(jvm shutdown)时自动做一些操作 */ @Override public void registerShutdownHook() { if (this.shutdown

chy-x 的博客 2825

学Simulink--基础光伏储能场景实例:基于Simulink的光储微电网主从控制策略仿真

摘要:本文详细介绍基于Simulink的光储微电网主从控制策略仿真方法。通过"储能V/f控制+光伏PQ控制"架构,实现孤岛运行时电压频率稳定和功率平衡。文章包含系统建模步骤、核心控制算法实现(附MATLAB代码)、三种典型工况仿真测试(稳态、光伏突变、负荷波动),结果显示系统满足电压偏差<±2.5%、频率偏差<±0.3%、动态响应<1s的性能要求。最后提出双主冗余、分层控制等优化方向,为光储微电网控制提供完整仿真解决方案。

amy_mhd的博客 74

自定义载板RK3588HDMI输入配置完整解决方案

✅ HDMI输入信号检测✅ 自动时序识别(支持1080p@60Hz等标准格式)✅ V4L2视频设备接口✅ 实时视频流捕获✅ H.264编码录制✅ HDCP内容保护支持问题根因识别:发现了hdmim1模块资源冲突的本质问题硬件设计理解:明确了Orange Pi 5 Plus的真实硬件设计意图功能实现:成功启用HDMI输入功能,替代了无法使用的HDMI1输出完整验证:建立了从硬件检测到视频录制的完整测试流程。

梁俊星的博客 1271

Spring《二》bean的实例化与生命周期

本文介绍了bean的3种实例化与生命周期。我们了解了bean是如何创建的,bean的生命周期是什么。 🍎道阻且长,行则将至。🍓!!!

Super algorithm 的博客,技术爱好者。 2033

廖雪峰Python教程[完整版]

廖雪峰的python教程整理的,已经排好版了,而且还是完整的,适合小白

bean的生命周期

bean的生命周期

m0_72963823的博客 263

lwip-2.0.3

lwip是瑞典计算机科学院(SICS)的Adam Dunkels 开发的一个小型开源的TCP/IP协议栈。实现的重点是在保持TCP协议主要功能的基础上减少对RAM 的占用。

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

聊聊 Spring 中最常用的 11 个扩展点?

spring mvc拦截器根spring拦截器相比,它里面能够获取和等web对象实例。,包含三个方法:preHandle 目标方法执行前执行postHandle 目标方法执行后执行afterCompletion 请求完成时执行为了方便我们一般情况会用接口的实现类类。假如有权限认证、日志、统计的场景,可以使用该拦截器。第一步,继承@OverrideSystem.out.println("===权限校验===");

cxytony的博客 287

最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版

Part-E1-SDIO-Specification-Ver4.00-Final-120220.pdf:最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版,包括SDIO 接口的外设,SDIO 接口官方协议等。

mini-spring|向虚拟机注册钩子,实现Bean对象的初始化和销毁方法

*** Bean 处理了属性填充后调用InitializingBean、DisposableBean,两个接口方法还是比较常用的,在一些需要结合 Spring 实现的组件中,经常会使用这两个方法来做一些参数的初始化和销毁操作。比如接口暴漏、数据库数据读取、配置文件加载等等。在 BeanDefinition 新增加了两个属性:initMethodName、destroyMethodName,

weixin_44925329的博客 1103

spring:bean的销毁

登记需要执行销毁方法的bean 在bean装配里面提过,bean初始化完成之后,会注册成为DisposableBean,这个DisposableBean就是关闭的时候,调用其destroy方法来销毁bean AbstractBeanFactory#registerDisposableBeanIfNecessary 重点是requiresDestruction方法,用来判断是否需要手动调用销毁方法,...

name_z的专栏 822

Spring中Bean初始化与销毁实现

本文结合源码讲解了Spring中Bean的初始化和销毁实现。

weixin_45749194的博客 971

spring DisposableBean作用,在spring Bean销毁时的钩子 以及@PreDestroy

在Spring框架中,DisposableBean是一个接口,它定义了一个单一的方法,用于在Spring容器关闭时或一个由Spring管理的Bean不再需要时执行特定的清理操作。DisposableBean接口在Spring框架中用于定义Bean的销毁逻辑,允许开发者在Bean生命周期结束时执行必要的资源释放、清理工作,以保证应用程序的健壮性和系统资源的有效管理。在Spring的XML配置文件中,可以直接为某个元素指定一个destroy-method属性,其值为Bean类中需要在销毁时调用的方法名。

weixin_44131922的博客 1631

Spring中Bean初始化和销毁的多种方式

详细介绍多种初始化Bean和销毁Bean的方式

初心不忘、始终方得 2476

科普文:Java基础Spring系列之【spring钩子函数汇总以及Spring Bean 的生命周期】

Spring作为当前Java最流行、最强大的轻量级框架,受到了程序员的热烈欢迎。准确的了解Spring Bean的生命周期是非常必要的。我们通常使用ApplicationContext作为Spring容器。这里,我们讲的也是 ApplicationContext中Bean的生命周期。而实际上BeanFactory也是差不多的,只不过处理器需要手动注册。

为无为,事无事,味无味。 1250

Spring优雅关闭之:ShutDownHook

前言: 又是一个之前没关注过的课题,发现学习Spring官方文档还是有用的,一个个的知识点不断冒出来。 意外的发现朱小厮https://blog.youkuaiyun.com/u013256816/大神也是优快云重度患者,哈哈,向大神学习,好好写博客,应该有一天也可以出书的吧。 闲话不多说了,先提出一个问题,什么叫做优雅关闭? 我们的java程序运行在JVM上...

恐龙弟旺仔的博客 3万+
上一篇: Spring4.1 AOP AspectJ支持包下载
下一篇: Spring AOP 需要包含的各种包
大树叶
博客等级 码龄12年 1171粉丝 664原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值