我是靠谱客的博主 合适洋葱,这篇文章主要介绍SpringBoot启动时任务,实现ApplicationRunner和CommandLineRunner接口的简单分析,现在分享给大家,希望可以做个参考。
我们都知道,springboot做初始化任务的时候可以实现ApplicationRunner
和CommandLineRunner
接口,重写run方法来完成。
复制代码
1
2
3
4
5
6
7public class MyStarter1 implements ApplicationRunner { @Override public void run(ApplicationArguments args) throws Exception { // do something } }
复制代码
1
2
3
4
5
6
7public class MyStarter2 implements CommandLineRunner { @Override public void run(String... args) throws Exception { // do something } }
可以看到,虽然都是run方法,但是参数是不同的。这里通过源码看一下这两者的区别。
首先是CommandLineRunner
,查看源码
复制代码
1
2
3
4
5
6package org.springframework.boot; @FunctionalInterface public interface CommandLineRunner { void run(String... args) throws Exception; }
发现除了我们自定义的实现,该接口没有任何实现,那么说明,这个接口的功能就是为了在程序启动时方便开发人员做一些初始化的操作。
再看ApplicationRunner
,查看源码
复制代码
1
2
3
4
5@FunctionalInterface public interface ApplicationRunner { void run(ApplicationArguments args) throws Exception; }
此类有内部实现JobLauncherApplicationRunner
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26public class JobLauncherApplicationRunner implements ApplicationRunner, Ordered, ApplicationEventPublisherAware { // .... // 入口 public void run(ApplicationArguments args) throws Exception { String[] jobArguments = (String[])args.getNonOptionArgs().toArray(new String[0]); this.run(jobArguments); } // 调用此方法 protected void launchJobFromProperties(Properties properties) throws JobExecutionException { JobParameters jobParameters = this.converter.getJobParameters(properties); // 执行任务 this.executeLocalJobs(jobParameters); // 注册任务 this.executeRegisteredJobs(jobParameters); } // 执行任务调用此方法 protected void execute(Job job, JobParameters jobParameters) throws JobExecutionAlreadyRunningException, JobRestartException, JobInstanceAlreadyCompleteException, JobParametersInvalidException, JobParametersNotFoundException { JobParameters parameters = this.getNextJobParameters(job, jobParameters); JobExecution execution = this.jobLauncher.run(job, parameters); // 发布事件 if (this.publisher != null) { this.publisher.publishEvent(new JobExecutionEvent(execution)); } } }
看一下传入的JobExecutionEvent
,实现了ApplicationEvent
复制代码
1
2
3
4
5
6
7
8
9
10
11public class JobExecutionEvent extends ApplicationEvent { private final JobExecution execution; public JobExecutionEvent(JobExecution execution) { super(execution); this.execution = execution; } public JobExecution getJobExecution() { return this.execution; } }
从上面的源码可以看出,CommandLineRunner
的作用比较单纯,就是执行一个启动时任务,没有做什么额外的事情。ApplicationRunner
则功能更丰富一点,可以把它的run方法当作一个任务,该任务会被注册到容器内,通过ApplicationListener
监听可以捕捉到这个任务的执行。
最后
以上就是合适洋葱最近收集整理的关于SpringBoot启动时任务,实现ApplicationRunner和CommandLineRunner接口的简单分析的全部内容,更多相关SpringBoot启动时任务,实现ApplicationRunner和CommandLineRunner接口内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复