PHP8.1.21版本已发布
vue8.1.21版本已发布
jquery8.1.21版本已发布

Spring boot CommandLineRunner启动任务传参的方法

WBOY
WBOY 转载
2023-05-12 12:43:06 802浏览

前言

有人可能有以为,这run(String... args)方法中的args参数是什么?

@Component
@Order(value = 1) // 指定其执行顺序,值越小优先级越高
public class MyRunner1 implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        System.out.println("MyRunner1");
    }
}

String... args是应用启动的时候可以传进来的参数,有两种方式可以传参

一种是命令行的方式传参,所以为什么这个接口叫CommandLineRunner

另一种方法是通过IntelliJ IDEA配置参数

下面分别说明

命令行传参

首先将应用打成jar包,然后运行如下命令行,我这里传入三个参数

java -jar MyProject.jar 野猿新一 野猿新二 野猿新三

IntelliJ IDEA传参

如果是在开发过程中想通过IntelliJ IDEA直接运行项目,不想打成jar包,又要传入参数,可以配置项目运行的环境

1.点击Edit Configurations...打开项目运行配置对话框

Spring boot CommandLineRunner启动任务传参的方法

2展开Environment,在Program arguments项中填入项目运行的参数,点击OK按钮确定

Spring boot CommandLineRunner启动任务传参的方法

测试

我们将上面的实例稍微修改下,把参数args打印出来

@Component
@Order(value = 1) // 指定其执行顺序,值越小优先级越高
public class MyRunner1 implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        System.out.println("MyRunner1:" + Arrays.toString(args));
    }
}

采用以上命令行的方式或者IntelliJ IDEA配置参数的方式运行结果一样,如下

2020-08-21 16:36:04.453 custom-logback INFO 16244 --- [ main] com.yeyuanxinyi.MyApplication : Started MyApplication in 10.724 seconds (JVM running for 13.727)
MyRunner1:[野猿新一, 野猿新二, 野猿新三]

以上就是Spring boot CommandLineRunner启动任务传参的方法的详细内容,更多请关注php中文网其它相关文章!

声明:本文转载于:亿速云,如有侵犯,请联系admin@php.cn删除