SpringBoot - @PostConstruct、InitializingBean、 ApplicationRunner 和 CommandLineRunner的执行顺序

Spring初始化之ApplicationRunner、InitializingBean、@PostConstruct执行顺序问题 Spring初始化之ApplicationRunner、InitializingBean、@PostConstruct执行顺序问题前言一、ApplicationRunner 接口的用法二、InitializingBean接口的用法三、@PostConstruct注解的用法三者在Spring项目启动的执行顺序: 前言 因为要用到Spring的初始化加载bean,比如Spring上下文的获取类应该优先加载,监听什么的类应该在启动后加载,所以考虑先后顺序,所以研究一下ApplicationRunner、Init 阅读详情

写在前面

在实际开发场景中,经常会遇到数据初始化的业务场景,那么如何在Spring容器启动时执行相关操作呢?比如:读取配置文件,数据库连接,数据缓存,数据预计算…
可以使用:@PostConstruct、InitializingBean、 ApplicationRunner 和 CommandLineRunner来完成。

SpringBoot - @PostConstruct 注解详解
SpringBoot - ApplicationRunner的作用是什么?
SpringBoot - InitializingBean的作用是什么?

测试示例

@Component
public class MyInitializingBean implements InitializingBean, CommandLineRunner, ApplicationRunner {
    @PostConstruct
    public void init() {
        System.out.println("1. 执行@PostConstruct注解的方法 - init()...");
    }


    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("2. 执行实现InitializingBean接口的方法 - afterPropertiesSet()...");
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println("3. 执行实现ApplicationRunner接口的方法 - run(ApplicationArguments args)...");

    }

    @Override
    public void run(String... args) throws Exception {
        System.out.println("4. 执行实现CommandLineRunner接口的方法 - run(String... args)...");
    }
}

// 输出结果如下:

1. 执行@PostConstruct注解的方法 - init()...
2. 执行实现InitializingBean接口的方法 - afterPropertiesSet()...
3. 执行实现ApplicationRunner接口的方法 - run(ApplicationArguments args)...
4. 执行实现CommandLineRunner接口的方法 - run(String... args)...

区别描述

A. 如果需要在容器启动后进行一些初始化操作,可以使用由SpringBoot提供的ApplicationRunner/CommandLineRunner;
B. 如果需要在一个类加载的时候进行一个初始化的操作,可以选择由JDK提供的@PostConstruct注解进行一个初始化的操作。另:@PostConstruct可以在容器没有完全启动的情况下能够进行初始化操作,而ApplicationRunner/CommandLineRunner的初始化一定是在容器完全启动之后执行的。@PostConstruct这个注解是针对BEAN的初始化完成之后再做一些事情,比如注册一些监听器、配置文件的初始化等等;
C. 由Spring提供的InitializingBean用法与@PostConstruct基本一致,但是相应的BEAN需要实现afterPropertiesSet()方法;

定义来源

名称来源
ApplicationRunnerSpring Boot
CommandLineRunnerSpring Boot
InitializingBeanSpring
@PostConstructJDK

执行顺序

@PostConstruct > InitializingBean > ApplicationRunner > CommandLineRunner

源码、示例及DEMO

源码、示例及DEMO

启动时运行,CommandLineRunner,InitializingBean 实际应用中,我们会有在项目服务启动的时候就去加载一些数据或做一些事情这样的需求。  为了解决这样的问题,Spring Boot 为我们提供了一个方法,通过实现接口 CommandLineRunner 来实现。 很简单,只需要一个类就可以,无需其他配置。  创建实现接口 CommandLineRunner 的类 @Component //不添加@Component则不会运行该代码 //@Or... 阅读详情

相关推荐

从硅片到调试器:深入浅出芯片Debug电路设计(含DAP/TraceBuffer原理图解析)

本文深入探讨了芯片Debug电路设计的关键技术,重点解析了DAP接口和TraceBuffer的原理图实现。通过HPM6000等实际案例,详细介绍了现代SoC调试模块的架构演进、DAP硬件实现细节、Trace压缩算法以及多核调试的挑战与解决方案,为芯片设计者提供了宝贵的调试电路设计参考。

omega的博客 669

Spring Boot中多个PostConstruct注解执行顺序控制

多个类中使用@PostConstruct加载先后顺序,有时候Class A中@PostConstruct注解的方法中的代码执行,需要等待Class B中@PostConstruct 注解方法中的代码执行完后,拿到结果,才能执行,也就是中A中某些代码的执行需要依赖B中代码执后的结果,此时就需要B先执行完,再执行A,

涛哥是个大帅比 7755

使用Wireshark抓取用户在网站的登陆密码

(POST请求是浏览器向服务器提交数据的方式,我们的用户名和密码就是这样提交出去的),单击点开,发现我们的账号和密码,就被抓取到了,在。(注意哦,要去掉http和/,比如http://www.4399.com/,我们只需要记下4399.com即可)(这句话是筛选数据,就是只显示IP为我们要抓取网站的数据) ,点击右边的蓝色箭头。这就是Wireshark简单的抓取登录密码的教程,只适用于http协议的网站。”打开,是这个样子,上面的数据先不用管,我们先点击左上角红色的方块停止抓包。,然后回车,得到的IP为。

泡泡的博客 1万+

CommandLineRunner、ApplicationRunner、InitializingBean、@PostConstruct 执行顺序

CommandlineRunner、ApplicationRunner、InitializingBean、@PostConstruct 执行顺序

w3634839644的博客 4483

星链V3的2048条波束与1Tbps:多波束相控阵的工程代价

低轨卫星通信的容量提升,核心在于多波束相控阵天线的空间复用能力。相控阵通过控制大量天线单元的相位,可在同一阵面同时形成多条独立指向的波束,从而在有限频谱内成倍提升系统容量。星链V3宣称的2048条波束与1 Tbps汇聚吞吐量,正是基于这一原理:更多波束意味着更高的频率复用系数和更灵活的资源调度。但工程实现并非免费午餐,数字背后是供电、散热、重量、发射成本及运维复杂度的急剧攀升。从用户侧看,更精细的波束也带来切换频繁、低仰角衰减等新挑战。本文从多波束相控阵的基础原理出发,拆解波束形成、频谱复用和动态调度的工程

weixin_33462167的博客 361

VSCode玩转ESP-ADF音频开发:从环境搭建到成功播放MP3的避坑全流程

本文详细介绍了如何在VSCode环境下使用ESP-ADF框架进行ESP32音频开发,从环境搭建到成功播放MP3的全流程。重点解析了`IDF_PATH`和`ADF_PATH`的配置问题,以及如何解决`xTaskCreateRestrictedPinnedToCore`等常见编译错误,帮助开发者快速上手ESP-ADF音频开发。

weixin_42520909的博客 341

Spring初始化之ApplicationRunner、InitializingBean、@PostConstruct

Spring提供了三个在项目启动的时候,就可以执行一些代码的方法和注解 1.ApplicationRunner接口 2.InitializingBean接口 3.@PostConstruct注解 一、ApplicationRunner 接口的用法 ApplicationRunner : 是一个接口,里面定义一个run(ApplicationArguments args)方法,我们需要自己写一个类去实现这个这接口,并实现接口里面的run(ApplicationArguments args)方法。 二、Init

weixin_44887276的博客 1224

Oracle集群管理-19.3升级19.18 opatchauto总结(java报错,resume oneoffs缺失目录)

t. (那个认为补丁已经打上了,但是oneoffs目录里面没有。将安装包文件的权限全部改成777.就继续执行了上述命令 ,此时使用opatch lsinv也是报错 ,在正常执行opatchauto apply。1 创建目录,存放补丁包,并赋予权限。于是使用如下命令对补丁进行回滚。

oradbm的博客 1418

ApplicationRunner、InitializingBean、@PostConstruct 执行顺序

ApplicationRunner、InitializingBean、@PostConstruct 执行顺序

_江屿_ 1575

毫米波雷达入门知识

毫米波雷达入门知识

ssbzxcvbnm1234567的博客 5457

inferCNV包安装问题及解决办法

InferCNV是一个由broad研究所开发的,利用单细胞转录组数据分析肿瘤细胞拷贝数变异(CNV)的工具。基本思路是在整个基因组范围内,通过计算肿瘤细胞关于参考的“正常”细胞的相对表达,利用滑窗思想对邻近的基因相对表达,计算拷贝数。 先贴一个官方安装说明: 官方infercnv安装说明 安装infercnv包: if (!requireNamespace("BiocManager", quietly = TRUE)) install.packages("BiocManager") BiocManager:

m0_51042606的博客 6805

@PostConstruct、InitializingBean、 ApplicationRunner 和 CommandLineRunner的执行顺序

@PostConstruct、InitializingBean、 ApplicationRunner 和 CommandLineRunner的执行顺序

u014644574的博客 1295

攻防世界 web高手进阶区 9分题 Web_python_flask_sql_injection

继续ctf的旅程,开始攻防世界web高手进阶区的9分题,本文是Web_python_flask_sql_injection的writeup

闵行小鱼塘 1481

@PostConstruct、InitializingBean、CommandLineRunner、ApplicationRunner加载顺序说明

@PostConstruct、InitializingBean、CommandLineRunner、ApplicationRunner加载顺序

weixin_40511641的博客 924

visio安装包

Microsoft Office Visio 是一款专业的制图软件。利用经过更新的形状、协作工具和数据链接图表,创建专业级图表以简化复杂的信息。

vb 6.0并口开发操作实例

vb6并口开发,简体中文,试例内有inpout32.dll动态链接库

如何在 SpringBoot 启动时执行特定代码?有哪些方式?

在Spring Boot启动时执行特定代码,常见于数据初始化、资源加载、缓存预热等场景。

weixin_43521001的博客 430

C# WinForm 基于DirectShow.dll编写的程序,可边预览边保存视频,音频和图片

基于微软的DirectShow.dll的二次开发1.自动识别连接的摄像头跟麦克风且可以对其进行选择(默认选中第一个)2.可录制wmv和avi两种格式的视频并且都带有音频,avi可以录制的分辨率和帧数进行选择,wmv默认进行了淸晰度优化如不喜欢可去除代码中有相关提示3.可在预览点开之后进行拍照,也可边录制视频边拍照4.添加了视频和音频的压缩功能(酌情使用)这次二次开发发现C#对DirectShow的相关信息太少,这次做完也不敢藏私共享出来,还望大家指正

如何让SpringBoot启动后执行某个方法

在日常开发中,我们很可能会遇到这样的需求:在项目启动后做某件事情,接下来本文将举例分析几个可以参考的做法

qq_41048524的博客 2391

深度学习工具包 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")

Java面试必备:如何在SpringBoot启动时执行特定代码?有哪些方式?

在SpringBoot应用开发中,我们经常需要在应用启动时执行一些初始化代码,比如加载配置、初始化数据库连接、预热缓存等。SpringBoot提供了多种方式来实现这一需求。本文将详细介绍这些方法,并通过流程图帮助理解它们的执行机制。

qq_58299462的博客 1597

SpringBoot启动时执行自定义内容的5种方法

SpringBoot提供了5种在启动时执行自定义逻辑的方法:1. CommandLineRunner/ApplicationRunner(推荐),支持顺序控制,适用于应用完全启动后的初始化;2. @PostConstruct,简单易用,适用于单个Bean初始化后执行;3. ApplicationListener,可监听特定启动事件,精确控制执行时机;4. InitializingBean,在Bean属性设置后执行;5. main方法直接执行,仅适合极简单场景。开发者可根据需求选择合适方案,其中前两种是官方

~ 870

Springboot 初始化操作

在使用Springboot过程中,或多或少我们会遇到在Springboot启动时要初始化类,或者加载文件之类的一些操作

做一个有思想的技术人 1316

需要在SpringBoot启动的时候执行一些内容。比如读取配置文件,数据库连接之类的 , 实现方式:CommandLineRunner,ApplicationRunner,@PostConstruct

开发中可能会有这样的场景,需要在容器启动的时候执行一些内容。比如读取配置文件,数据库连接之类的。SpringBoot给我们提供了两个接口来帮助我们实现这种需求,两个启动加载接口分别是:CommandLineRunner和ApplicationRunner。Spring 提供了接口 InitializingBean,jdk提供了@PostConstruct.

小哇 419

探秘Spring Boot中的8种初始化操作方式和执行顺序

在 Spring Boot 中,选择合适的初始化方式取决于你的具体需求和初始化逻辑的复杂程度。和适合早期的、简单的初始化操作,而和更适合在应用完全启动后执行的复杂逻辑。了解这些初始化方式的执行顺序和特点,能够帮助你在项目中做出最佳选择,确保应用的平稳启动。希望本文能帮助你更好地理解和应用 Spring Boot 中的初始化操作,让你的项目在启动过程中更加高效和可靠。如果你对 Spring Boot 还有其他问题或建议,欢迎在评论区交流。

weixin_40642302的博客 1683

Spingboot启动后自动初始化的几种方式

ApplicationRunner 与CommandLineRunner工作方式相同,唯一的区别在于两种方法入参方式不同,实现这两个接口就可以让应用程序代码在启动完成后,接收流量前被调用。InitializingBean接口只包含afterProperiesSet()这一个方法,凡是继承InitializingBean接口的类,都会在初始化的时候调用这个方法;作用在于声明一个Bean对象初始化完成后执行的,方法比ApplicationRunner要快。2、被注解的方法不得有任何参数。

qq_41759440的博客 1220

Spring Boot中的类初始化方法的执行先后顺序

启动Spring Boot服务,其中类的初始化方法的执行具有先后顺序,经验证,执行先后顺序如下:SpringApplication>ServletContextListener>InitializingBean>PostConstruct>ApplicationRunner>CommandLineRunner

积跬步,至千里。 2569

[Java Framework] SpringBoot几种启动后自动初始化的几种方式

业务需求需要在项目启动之后自动把执行一次方法 (数据初始化或者创建一些调度任务),但是有时候可能不太明确他们的执行顺序,本文就带你梳理一下它们的执行顺序。

OxYGC 2117
上一篇: SpringBoot - @PostConstruct 注解详解
下一篇: SpringBoot - HttpServletRequestWrapper的使用场景
cloneme01
博客等级 码龄20年 2万+粉丝 248原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

cloneme01

谢谢您的支持与鼓励!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值
⌂ 换网址