spring在web容器启动时执行初始化方法

【全解析 | PTA】浙大版《Python 程序设计》题目集-第一章 Python浙大版PTA题解 阅读详情

需求:在tomcat启动时开启一个定时任务。

想法:容器启动时执行方法,最容易想到的就是servlet中可以配置load-on-startup,设置一个正整数也就可以随容器一起启动。

问题:上面的方法很好,但是由于定时任务需要去操作数据库,而项目采用了spring的依赖注入来管理对象,而servlet并不受Spring的管理。若此时在servlet中注入Spring管理的对象,则会报错:javax.naming.NameNotFoundException: Name com.test.InitServlet is not bound in this Context。

所以想要再servlet中操作数据库,只能手动去创建一个service,这显然违背了我们使用Spring的初衷,让项目看起来不伦不类的。那么如何才能在启动WEB容器的时候执行一段初始化代码,并且可以让其被Spring管理呢?

解决方案:Spring提供了当一个Bean初始化后执行方法的扩展点:InitializingBean。这里的初始化指的就是当该Bean的属性被注入完成后(注意:这里并不是所有属性都需要被设置),所以InitializingBean接口提供的方法名称也很形象:afterPropertiesSet()。

使用的时,将该Bean注入到Spring容器,之后我们便可以获得Spring容器中的对象了,也就是说,可以得到service方法来执行我们的定时任务了。

具体代码如下:

@Component
public class InitServlet implements InitializingBean {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	@Resource
	private DispatchesService dispatchesService;

	@Override
	public void afterPropertiesSet() throws Exception {
	<span style="white-space:pre">	</span>dispatchesService.spyDDetails();
	}

}

另外还有两种方法也可以实现如上的功能。

1、若采用XML来配置Bean的话,可以指定属性init-method

2、通过注解@PostConstruct来修改初始化方法

值得注意的是,三者可以同时存在,触发的顺序是先触发@PostConstruct修饰的方法,再触发afterPropertiesSet(),最后触发init-method

其中@PostConstruct是通过注册一个BeanPostProcessor,在Bean的初始化方法之前调用,而afterPropertiesSet()和init-method都在初始化方法中调用

关于@PostConstruct详细的介绍可以看这里:http://blog.csdn.net/yaerfeng/article/details/8447530

下面是Spring中调用Bean的初始化代码的源代码:

	protected void invokeInitMethods(String beanName, final Object bean, RootBeanDefinition mbd)
			throws Throwable {

		boolean isInitializingBean = (bean instanceof InitializingBean);
		if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {
			if (logger.isDebugEnabled()) {
				logger.debug("Invoking afterPropertiesSet() on bean with name '" + beanName + "'");
			}
			if (System.getSecurityManager() != null) {
				try {
					AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
						public Object run() throws Exception {
							((InitializingBean) bean).afterPropertiesSet();<span style="white-space:pre">	</span><span style="font-family: Arial, Helvetica, sans-serif;">// 这里触发afterPropertiesSet</span><span style="white-space:pre">
</span>
							return null;
						}
					}, getAccessControlContext());
				}
				catch (PrivilegedActionException pae) {
					throw pae.getException();
				}
			}				
			else {
				((InitializingBean) bean).afterPropertiesSet();<span style="white-space:pre">	</span>// 这里触发afterPropertiesSet
			}
		}

		if (mbd != null) {
			String initMethodName = mbd.getInitMethodName();// 这里是触发init-method
			if (initMethodName != null && !(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
					!mbd.isExternallyManagedInitMethod(initMethodName)) {
				invokeCustomInitMethod(beanName, bean, mbd);
			}
		}
	}


补充:

还有一种方法,是当Spring将所有的Bean都初始化完成后,会留给我们一个入口,我们可以实现如下接口

@Component
public class InstantiationTracingBeanPostProcessor implements
		ApplicationListener<ContextRefreshedEvent> {

	@Override
	public void onApplicationEvent(ContextRefreshedEvent arg0) {
		System.out.println("-----所有Bean载入完成---");
	}
}


李宏毅机器学习笔记第17周_概述领域自适应(Domain Adaptation) Domain Adaptation 阅读详情

相关推荐

Vivado FFT IP核避坑指南:从Matlab数据生成到FPGA验证的完整流程

本文详细解析了Vivado FFT IP核从Matlab数据生成到FPGA验证的完整流程,重点解决跨平台数据一致性、IP核配置陷阱和验证方法论等核心问题。通过实战案例和避坑指南,帮助工程师高效实现FFT运算的硬件验证,确保结果与Matlab的误差控制在0.3%以内。

weixin_42543046的博客 402

Spring启动后进行一些初始化的方式汇总

spring启动后初始化操作的方式

weixin_44368487的博客 2133

Python Selenium自动化浏览器实战:从环境搭建到高级技巧

浏览器自动化是现代软件开发与数据处理中的关键技术,它通过程序模拟用户操作,实现网页交互的自动化执行。其核心原理是基于WebDriver协议,通过驱动程序与浏览器进行通信,从而控制浏览器的各种行为。这项技术的价值在于能够将重复性高、耗时长的Web操作转化为可编程、可复用的脚本,极大提升工作效率和准确性。在应用场景上,它广泛覆盖了Web自动化测试、数据采集与爬虫、日常办公流程自动化以及RPA(机器人流程自动化)等多个领域。本文聚焦于Python环境下Selenium这一经典工具,深入讲解其环境配置、八大元素定位

anwenzhao0749的博客 449

SpringMVC系列-1 使用方式和启动流程

当Tomcat被部署到服务器或者通过本地IDEA将项目war包通过local tomcat部署到Tomcat上后,可以通过startup.sh或者startup.bat触发Bootstrap的main方法,从而开启Tomcat容器组件的初始化和启动过程。从宏观上看,启动过程中对应着Listener-> Filter -> Servlet组件的触发流程。本文涉及的组件包括Listener和Servlet:Tomcat在构造Context实例后会触发ServletContextEvent事件

shengyu 6500

获取微信公众号历史文章列表页链接

action=home&__biz=这里替换你的biz==4、链接分享、发送到微信即可访问,注意该链接仅可在微信客户端使用,外部浏览器无法打开。3、拼接通用公式生成链接即为微信公众号历史文章列表链接。,如下图找到红框部分值,复制即为上文biz值。2、浏览器右键查看网页源码,新开页面搜索(1、复制公众号任意文章的链接在浏览器打开。

珞瑜的博客 8000

通俗范畴论10 泛性质(MD版)

既然泛性质可以在同构意义下唯一确定一个泛构造,那么我们就可以用泛性质来定义泛构造。我们回顾一下已经掌握的泛性质和泛构造。泛性质其实我们并不陌生,始对象和终对象,就是具有泛性质的对象,一个具有“始”的泛性质,一个具有“终”的泛性质。比如始对象,如果一个范畴里面有始对象,它到所有对象都有且只有一个态射,这样的对象可能有两个么?嗯,还真可能,但是这两个始对象同构,所以在同构意义下,它们可以看成一个,因此在同构意义下,始对象是唯一的。同理,终对象也一样。同构的始对象。

RockTec的专栏 483

Spring Boot启动时执行初始化操作的几种方式

Spring Boot启动时执行初始化操作的几种方式

strggle_bin的博客 5274

A2A 协议详解:Agent Card 的设计与实现

Agent Card 是 Agent2Agent (A2A) 协议中实现智能体发现与互操作性的核心组件。本文将深入剖析 Agent Card 的设计理念、关键字段及其在智能体生态系统中的作用。我们将通过详细的 JSON Schema 解析和 Python SDK 示例,帮助您理解如何精确地定义和发布智能体能力,为构建可发现、可协作的 AI 智能体奠定基础。当您使用a2a.Agent类初始化一个智能体时,SDK 会根据您提供的参数(nameversion等)自动构建内部的 Agent Card 表示。

加入“Super Entity”,与全能开发团队共探AI智能体与数字人项目,开启前沿技术之旅。 1489

springmvc初始化过程

本文一起看下springMVC的初始化过程。当我们按照如下的步骤配置好springmvc的环境后,就可以启动tomcat来访问项目了:在启动tomcat的过程中会对springmvc的环境进行初始化,入口自然是DispatcherServlet的init方法。在servlet规范中,加载servlet后,会调用其init方法,当加载DispatcherServlet时,最终会调用到springmvc的servlet处参考。

wang0907的博客 409

RT-DETR改进策略【卷积层】| CGblock 内容引导网络 利用不同层次信息,提高多类别分类能力 (含二次创新)

本文记录的是利用中的模块优化的目标检测网络模型。通过局部特征提取器、周围环境提取器、联合特征提取器和全局环境提取器来提取局部特征、周围环境和全局环境信息,充分利用不同层次的信息。本文将其应用到中,并进行二次创新,使网络能够更好的处理多类别目标的分类能力。CGNet: A Light-Weight Context Guided Network for Semantic Segmentation1️⃣ 首先通过局部特征提取器floc(∗)floc(*)floc(∗)和周围环境提取器fsur(∗)f_{sur }

Limiiiing的博客 1357

SAR成像专栏目录

为方便大家阅读,我做了一个专栏目录,蓝色字有超链接,可以直接打开。 本专栏默认读者已具备雷达系统的基本知识或者已阅读过雷达导论专栏中的文章。 1. 概述 SAR成像概述 星载SAR的各项指标解读(史上最全) SAR成像算法的实现途径与算力分析 2. SAR成像原理与SAR系统简介 雷达与分辨率 SAR成像原理与方法 SAR图像的形成和处理 SAR系统设计 3. 点目标仿真 点目标仿真(一)—— 数学模型 点目标仿真(二)—— Matlab仿真 4. 成像算法 更新中 雷达导论专

7503

SpringMVC源码分析:SpringMVC初始化(一)

SpringMVC的初始化大概分为Spring的初始化和SpringMVC的初始化两个部分,他们之间的关系如下图。下面我将按照这个顺序进行详细介绍。

weixin_55229531的博客 5万+

喷涂机器人系列编程:ABB IRB 5500_(2).ABB IRB 5500喷涂机器人系统架构与组件

ABB IRB 5500喷涂机器人系统不仅在性能上表现出色,而且在安全和维护方面也提供了全面的解决方案。通过本文的详细介绍,希望读者能够更好地理解和掌握这一系统的架构和功能,为实际应用提供有力支持。

zhubeibei168的博客 783

spring在web容器启动时执行初始化方法(四种方式)

需求:在tomcat启动时开启一个定时任务,或初始化slor索引 想法:容器启动时执行方法,最容易想到的就是servlet中可以配置load-on-startup,设置一个正整数也就可以随容器一起启动。 问题:上面的方法很好,但是由于定时任务需要去操作数据库,而项目采用了spring的依赖注入来管理对象,而servlet并不受Spring的管理。若此时在servlet中注入

zl的博客 8615

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

老版QQ原生表情gif动态

这是老版的QQ表情,不过全是动态的的,Windows照片查看器是不会动的,可以右击用浏览器打开查看,再说一遍是老版的,只是分享给宁愿用老版也要动态的人。

Spring在Web容器启动时执行初始化方法

需求:在tomcat启动时开启一个定时任务。想法:容器启动时执行方法,最容易想到的就是servlet中可以配置load-on-startup,设置一个正整数也就可以随容器一起启动。问题:上面的方法很好,但是由于定时任务需要去操作数据库,而项目采用了spring的依赖注入来管理对象,而servlet并不受Spring的管理。若此时在servlet中注入Spring管理的对象,则会报错:javax.n...

Evan 946

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

java web 服务启动初始化类_spring 在web容器启动时执行初始化方法

开发框架:spingMVC+myBatis解决方案:给web容器添加一个Listener类,在容器启动的时候执行Listener的“初始化”方法,在这个初始化方法中执行查询数据库的所有操作,然后将数据库中的信息缓存起来问题:上面的方法很好,但问题是如何去查询数据库,由于使用了spring的IOC特性,查询数据库的service控制dao层,dao层访问数据库,而Listener类只是在系统启动的时...

weixin_32085599的博客 513

深度学习工具包 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 在web 容器启动时,执行FIFO队列初始化方法

解决方案:web容器添加一个Listener类,在容器启动的时候执行Listener的“初始化”方法,在这个初始化方法中执行FIFO队列的初始化工作。 解决方法:spring给出的解决方案——写一个类,实现InitializingBean接口,然后交由spring容器管理。 示例代码: package com.settlement.initialization; import ja

zhouzhiwengang的专栏 1668

spring 在web容器启动时执行初始化方法

2019独角兽企业重金招聘Python工程师标准>>> ...

weixin_34148456的博客 149

java 项目启动初始化_Spring项目启动时执行初始化方法

一、applicationContext.xml配置beaninit-method="initKeyWord">classpath:sensitive-word.xml说明:bean:class为需要执行的类init-method对应该类需要执行的方法property:name对应类中需要注入的属性对象(必须设置set方法,否则无法注入)value为注入的值二、执行的类Sensitiv...

weixin_28860509的博客 2586

Spring容器初始化后执行的方法

在项目中, 会遇到要在容器加载完就做一些初始化, 例如Quartz的监听器重新注册(Quartz监听器在RAM中的, Web容器重启或关闭会丢失)等需求。   import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextRefreshedEvent

wenniuwuren 1975
上一篇: 好多东西都没记录,罪过啊~
下一篇: 三种思路实现自定义404页面
百里马
博客等级 码龄13年 401粉丝 211原创
评论 5
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值