应用启动数据初始化接口CommandLineRunner和Application详解_第1页
应用启动数据初始化接口CommandLineRunner和Application详解_第2页
应用启动数据初始化接口CommandLineRunner和Application详解_第3页
应用启动数据初始化接口CommandLineRunner和Application详解_第4页
应用启动数据初始化接口CommandLineRunner和Application详解_第5页
已阅读5页,还剩3页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

第应用启动数据初始化接口CommandLineRunner和Application详解目录应用启动数据初始化接口CommandLineRunner和Application详解1运行时机2实现接口3执行顺序4设置启动参数5运行效果ApplicationRunner和CommandLineRunner用法区别ApplicationRunnerCommandLineRunner

应用启动数据初始化接口CommandLineRunner和Application详解

在SpringBoot项目中创建组件类实现CommandLineRunner或ApplicationRunner接口可实现在应用启动之后及时进行一些初始化操作,如缓存预热、索引重建等等类似一些数据初始化操作。

两个接口功能相同,都有个run方法需要重写,只是实现方法的参数不同。

CommandLineRunner接收原始的命令行启动参数,ApplicationRunner则将启动参数对象化。

1运行时机

两个接口都是在SpringBoot应用初始化好上下文之后运行,所以在运行过程中,可以使用上下文中的所有信息,例如一些Bean等等。在框架SpringApplication类源码的run方法中,可查看Runner的调用时机callRunners,如下:

*RuntheSpringapplication,creatingandrefreshinganew

*{@linkApplicationContext}.

*@paramargstheapplicationarguments(usuallypassedfromaJavamainmethod)

*@returnarunning{@linkApplicationContext}

publicConfigurableApplicationContextrun(String...args){

StopWatchstopWatch=newStopWatch();

stopWatch.start();

ConfigurableApplicationContextcontext=null;

CollectionSpringBootExceptionReporterexceptionReporters=newArrayList();

configureHeadlessProperty();

SpringApplicationRunListenerslisteners=getRunListeners(args);

listeners.starting();

try{

ApplicationArgumentsapplicationArguments=newDefaultApplicationArguments(args);

ConfigurableEnvironmentenvironment=prepareEnvironment(listeners,applicationArguments);

configureIgnoreBeanInfo(environment);

BannerprintedBanner=printBanner(environment);

context=createApplicationContext();

exceptionReporters=getSpringFactoriesInstances(SpringBootExceptionReporter.class,

newClass[]{ConfigurableApplicationContext.class},context);

prepareContext(context,environment,listeners,applicationArguments,printedBanner);

refreshContext(context);

afterRefresh(context,applicationArguments);

stopWatch.stop();

if(this.logStartupInfo){

newStartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(),stopWatch);

listeners.started(context);

//调用Runner,执行初始化操作

callRunners(context,applicationArguments);

catch(Throwableex){

handleRunFailure(context,ex,exceptionReporters,listeners);

thrownewIllegalStateException(ex);

try{

listeners.running(context);

catch(Throwableex){

handleRunFailure(context,ex,exceptionReporters,null);

thrownewIllegalStateException(ex);

returncontext;

2实现接口

2.1CommandLineRunner

简单实现如下,打印启动参数信息:

@Order(1)

@Component

publicclassCommandLineRunnerInitimplementsCommandLineRunner{

privateLoggerlogger=LoggerFactory.getLogger(this.getClass());

privatefinalStringLOG_PREFIX="CommandLineRunner";

@Override

publicvoidrun(String...args)throwsException{

try{

this.logger.error("{}args:{}",LOG_PREFIX,StringUtils.join(args,","));

}catch(Exceptione){

logger.error("CommandLineRunnerInitrunfailed",e);

2.2ApplicationRunner

简单实现如下,打印启动参数信息,并调用Bean的方法(查询用户数量):

@Order(2)

@Component

publicclassApplicationRunnerInitimplementsApplicationRunner{

privateLoggerlogger=LoggerFactory.getLogger(this.getClass());

privatefinalStringLOG_PREFIX="ApplicationRunner";

privatefinalUserRepositoryuserRepository;

publicApplicationRunnerInit(UserRepositoryuserRepository){

this.userRepository=userRepository;

@Override

publicvoidrun(ApplicationArgumentsargs)throwsException{

try{

this.logger.error("{}args:{}",LOG_PREFIX,JSONObject.toJSONString(args));

for(StringoptionName:args.getOptionNames()){

this.logger.error("{}argName:{}argValue:{}",LOG_PREFIX,optionName,args.getOptionValues(optionName));

this.logger.error("{}usercount:{}",LOG_PREFIX,this.userRepository.count());

}catch(Exceptione){

logger.error("CommandLineRunnerInitrunfailed",e);

3执行顺序

如果实现了多个Runner,默认会按照添加顺序先执行ApplicationRunner的实现再执行CommandLineRunner的实现,如果多个Runner之间的初始化逻辑有先后顺序,可在实现类添加@Order注解设置执行顺序,可在源码SpringApplication类的callRunners方法中查看,如下:

privatevoidcallRunners(ApplicationContextcontext,ApplicationArgumentsargs){

ListObjectrunners=newArrayList();

//先添加的ApplicationRunner实现

runners.addAll(context.getBeansOfType(ApplicationRunner.class).values());

//再添加的CommandLineRunner实现

runners.addAll(context.getBeansOfType(CommandLineRunner.class).values());

//如果设置了顺序,则按设定顺序重新排序

AnnotationAwareOrderComparator.sort(runners);

for(Objectrunner:newLinkedHashSet(runners)){

if(runnerinstanceofApplicationRunner){

callRunner((ApplicationRunner)runner,args);

if(runnerinstanceofCommandLineRunner){

callRunner((CommandLineRunner)runner,args);

}

4设置启动参数

为了便于对比效果,在Idea中设置启动参数如下图(生产环境中会自动读取命令行启动参数):

5运行效果

在上面的两个Runner中,设定了CommandLineRunnerInit是第一个,ApplicationRunnerInit是第二个。启动应用,运行效果如下图:

ApplicationRunner和CommandLineRunner用法区别

业务场景:

应用服务启动时,加载一些数据和执行一些应用的初始化动作。如:删除临时文件,清除缓存信息,读取配置文件信息,数据库连接等。

1、SpringBoot提供了CommandLineRunner和ApplicationRunner接口。当接口有多个实现类时,提供了@order注解实现自定义执行顺序,也可以实现Ordered接口来自定义顺序。

注意:数字越小,优先级越高,也就是@Order(1)注解的类会在@Order(2)注解的类之前执行。

两者的区别在于:

ApplicationRunner中run方法的参数为ApplicationArguments,而CommandLineRunner接口中run方法的参数为String数组。想要更详细地获取命令行参数,那就使用ApplicationRunner接口

ApplicationRunner

@Component

@Order(value=10)

publicclassAgentApplicationRun2implementsApplicationRunner{

@Override

publicvoidrun

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论