springboot项目启动后执行方法:CommandLineRunner和ApplicationRunner

介绍

springboot项目启动后执行指定方法,有几种实现方式,这里介绍常用的的 CommandLineRunner 和 ApplicationRunner

其他方法详见:
https://juejin.cn/post/7025858036002455589

执行顺序

  1. 默认是 ApplicationRunner 先执行

  2. 如果指定了 @Order,则按照 @Order 的大小顺序执行,大的先执行

CommandLineRunner(推荐)

实现 CommandLineRunner 接口,然后重写 run() 方法即可

优点:方法执行时,项目已经初始化完毕,是可以正常提供服务的。

源码

@FunctionalInterface
public interface CommandLineRunner {
    void run(String... args) throws Exception;
}

接收参数

项目启动时携带参数,如下:

java -jar demo.jar arg1 arg2 arg3

这些参数可以传递到 run 方法

关于参数传递详见:

https://blog.csdn.net/mqdxiaoxiao/article/details/108149272

例子

@Component
public class CommandLineRunnerImpl implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        System.out.println(Arrays.toString(args));
    }
}

实现ApplicationRunner接口

实现 ApplicationRunner 接口,然后重写 run() 方法即可

接收参数

项目启动时携带参数,如下:

java -jar demo.jar --name=李雷 --age=20

这些参数可以传递到 run 方法

注意:参数格式必须是:--key=value

例子

@Component
public class ApplicationRunnerImpl implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) throws Exception {
        Set<String> optionNames = args.getOptionNames();
        for (String optionName : optionNames) {
            List<String> values = args.getOptionValues(optionName);
            System.out.println(optionName+"--"+values);
        }
    }
}

idea测试:

https://www.jianshu.com/p/f80f833ab8f6
https://blog.csdn.net/qq_22310551/article/details/124296073


原文出处:/show_1IX4ze7WLlOs.html