前言
在项目完全启动前,可能需要初始化一些东西、加载数据或者执行一些任务等;SpringBoot提供了CommandLineRunner和ApplicationRunner接口,在容器启动成功后的最后进行回调,遍历所有实现了这两个接口的类加载到Spring 容器中,然后执行接口实现类中的run方法。可以用来预先校验数据,加载数据或者执行任务等等。
实现
使用CommandLineRunner,需要将其注入到spring容器中,所以可以通过@Component、在SpringBoot入口中实现该接口或者声明一个实现接口的bean,然后在启动时能够注入到spring容器中即可。
1.使用@Component注解
@Component
public class ExampleOne implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
// 可以写自己的业务代码
System.out.println("使用@component注解的方式");
}
}
注: 通过使用@Component注解,通过启动springBoot就可以扫描到这个接口实现类,无需再springBoot入口中在进行其他配置。
- 在SpringBoot入口中实现该接口
@SpringBootApplication
public class BootApplication implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(BootApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
System.out.println("在入口配置");
}
}
- 声明一个Bean
public class ExampleThree implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("通过Bean方法注入,可以实现自己 想要做的");
}
}
在入口中配置(其他位置也行,只要是能注入到Spring 容器中即可)
@SpringBootApplication
public class BootApplication {
public static void main(String[] args) {
SpringApplication.run(BootApplication.class, args);
}
@Bean
public ExampleThree test(){
return new ExampleThree();
}
}
实现接口后,如果run方法中的代码抛出异常的话会导致启动失败!核心地方try catch 一下。
多个实现类的执行顺序
当有多个类是实现了CommandLineRunner接口时,可以通过@Order注解指定他们的执行顺序。@Order(value = 1) value 的值越小,越先执行。
最后
实现类在应用成功启动后,去执行相关代码逻辑,且只会执行一次;
我们可以在run()方法里使用任何依赖,因为它们已经初始化好了;
关于ApplicationRunner接口,与CommandLineRunner接口大致相同,如果你需要访问ApplicationArguments去替换掉字符串数组,可以考虑使用ApplicationRunner类。
举例可查看博客地址:
https://www.jianshu.com/p/5d4ffe267596
遇到了,只是为了做个总结!step by step!
本文介绍SpringBoot中CommandLineRunner和ApplicationRunner接口的使用,通过@Component注解、在SpringBoot入口实现或声明Bean的方式,实现应用启动后执行特定任务。文章探讨了如何预先校验数据、加载数据或执行任务,并讲解了多个实现类的执行顺序控制。
1026

被折叠的 条评论
为什么被折叠?



