需求:SpringBoot项目启动成功后执行某方法
方案:在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