SpringBoot 启动时实现自动执行

#SpringBoot [字体 ··]

摘要:有时启动 springboot 项目后需要执行一些方法初始化,如资源加载、数据准备等,首先不能放在 main 方法中 SpringApplication.run()之前,因为此时 bean 还未初始化,除非你不使用 bean,当然也不能放其后,因为 run 方法执行后启动 tomcat 会阻塞在端口监听,run 方法后的代码不会执行。

一、如何实现

有两种方法。实现 ApplicationRunnerCommandLineRunner 接口。

示例:

1@Component
2public class Bootstrap implements ApplicationRunner {
3
4    @Override
5    public void run(ApplicationArguments args) throws Exception {
6				// 项目启动时自动执行此方法
7    }
8}
1@Component
2public class Bootstrap implements CommandLineRunner {
3
4    @Override
5    public void run(String... ) throws Exception {
6        // 项目启动自动执行此方法
7    }
8}

二、区别

共同点:他们都能实现在 springboot 项目启动时执行方法,并且只执行一次。如果实现多个 ApplicationRunnerCommandLineRunner ,可以通过 @Order 来指定执行顺序,值小优先执行。

示例:

 1@Component
 2@Order(1)
 3public class MyCommandLineRunner1 implements CommandLineRunner {
 4    @Override
 5    public void run(String... args) throws Exception {
 6        System.out.println("Runner1 - " + Arrays.toString(args));
 7    }
 8}
 9
10@Component
11@Order(2)
12public class MyCommandLineRunner2 implements CommandLineRunner {
13    @Override
14    public void run(String... args) throws Exception {
15        System.out.println("Runner2 - " + Arrays.toString(args));
16    }
17}

不同点:他们的不同点区别在 run 方法点入参,一个是 ApplicationArguments 对象,另一个是字符串数组。

CommandLineRunner 的入参和 main 方法一样。而 ApplicationRunner 的入参则被转换为 ApplicationArguments 对象,这个对象可以获取选项参数非选项参数,例如有一条命令:java -jar app.jar 127.0.0.1 8080 --env=prod

启动程序 main 入参是:

  1. 127.0.0.1
  2. 8080
  3. --env=prod

解释:

  1. 选项参数--env=prod
  2. 非选项参数127.0.0.18080

P.S. 选项参数即 K-V 型参数,非选项型参数即只有值的参数。


博客没有评论系统,可以通过 邮件 评论和交流。