剖析ApplicationRunner、CommandLineRunner

需求:SpringBoot项目启动成功后执行某方法
【剖析ApplicationRunner、CommandLineRunner】方案:在spring-boot中提供了两种Runner接口:ApplicationRunner和CommandLineRunner,编写自己的类实现这两种接口的run方法,均可实现需求
不同的是实现的两个run方法接收的参数不同,这也是他俩唯一的不同,
ApplicationRunner 接收的是 ApplicationArguments 类型的参数,即应用程序启动参数
CommandLineRunner 接收的是String类型的可变参数,它的值就是我们main函数接收到的命令行参数(此参数可通过Run Configurations中的Arguments添加)

Runner源码解析:SpringApplication.run 方法源代码执行成功的最后一步调用了 callRunners(context, applicationArguments),
此方法内部搜集了当前容器中所有的Runner类型的实体,并遍历调用其run方法,实现了后置的方法调用功能,具体源码如下

① SpringBoot主启动类:

public static void main(String[] args) { SpringApplication springApplication = new SpringApplication(CcwebApplication.class); springApplication.run(args); }

②run方法最后一步
public ConfigurableApplicationContext run(String... args) { ...listeners.started(context); // 寻找并调用当前容器中所有Runner this.callRunners(context, applicationArguments); ... }

③ 遍历执行所有Runner
private void callRunners(ApplicationContext context, ApplicationArguments args) { List runners = new ArrayList();
// 找到上下文中所有实现了ApplicationRunner的类 runners.addAll(context.getBeansOfType(ApplicationRunner.class).values());
// 找到上下文中所有实现了CommandLineRunner的类 runners.addAll(context.getBeansOfType(CommandLineRunner.class).values());
// 根据@Order注解的Value值进行排序 AnnotationAwareOrderComparator.sort(runners); Iterator var4 = (new LinkedHashSet(runners)).iterator(); // 依次调用run 方法 while(var4.hasNext()) { Object runner = var4.next(); if (runner instanceof ApplicationRunner) { this.callRunner((ApplicationRunner)runner, args); }if (runner instanceof CommandLineRunner) { this.callRunner((CommandLineRunner)runner, args); } }}

    推荐阅读