SpringBoot向CommandLineRunner传递参数

Cod*_*mer 1 command-line-arguments spring-boot

我正在使用SpringBoot 2.1.3并尝试通过命令行传递许多参数。

这是main课程:

@SpringBootApplication
@Slf4j
public class Application implements CommandLineRunner {

@Value("${priceOne.pound}")
private Integer p1pound;

@Value("${priceOne.shilling}")
private Integer p1shilling;

@Value("${priceOne.pences}")
private Integer p1pences;

@Value("${priceTwo.pound}")
private Integer p2pound;

@Value("${priceTwo.shilling}")
private Integer p2shilling;

@Value("${priceTwo.pences}")
private Integer p2pences;

@Value("${factor}")
private Integer factor;

@Value("${op}")
private String op;

public static void main(String[] args) {
    SpringApplication.run(EurisApplication.class, args);
}

@Override
public void run(String... args) {
    Price priceOne = new Price(p1pound, p1shilling, p1pences);
    Price priceTwo = new Price(p2pound, p2shilling, p2pences);
    ....
    ....
}
Run Code Online (Sandbox Code Playgroud)

我尝试用以下内容填充这些变量:

spring-boot:run -Drun.arguments=--priceOne.pound=5, --priceOne.shilling=5, --priceOne.pences=5, --priceTwo.pound=5, --priceTwo.shilling=5, --priceTwo.pences=5, --factor=0, --op=+
Run Code Online (Sandbox Code Playgroud)

或与:

spring-boot:run -Dspring-boot.run.arguments=--priceOne.pound=5, --priceOne.shilling=5, --priceOne.pences=5, --priceTwo.pound=5, --priceTwo.shilling=5, --priceTwo.pences=5, --factor=0, --op=+
Run Code Online (Sandbox Code Playgroud)

如果我" "在参数列表的开头和结尾添加引号,则会出现转换错误。

你能帮助我吗?

多谢。


感谢您的回复!

如果我删除除第一个参数之外的所有参数,然后使用以下命令启动应用程序:

 spring-boot:run -Dspring-boot.run.arguments=--priceOne.pound=5
Run Code Online (Sandbox Code Playgroud)

工作正常。您提到的其他方式:

 spring-boot:run --priceOne.pound=5
Run Code Online (Sandbox Code Playgroud)

使用一个参数和多个参数检索解析异常。我有点困惑..

我编写整个应用程序所花费的时间比编写那个该死的commandLine启动所花费的时间要少。我无法将所有参数作为一个参数获得String。我不明白为什么只有一个参数有效而两个参数无效!

谢谢

Nic*_*las 5

正如 @improbable 提到的,-Dspring-boot.run.arguments用于将参数传递给main()方法。

为了设置@Value属性,直接使用--语法:

spring-boot:run --priceOne.pound=5 --priceOne.shilling=5 --priceOne.pences=5, --priceTwo.pound=5 --priceTwo.shilling=5 --priceTwo.pences=5 --factor=0 --op=+
Run Code Online (Sandbox Code Playgroud)

请查看相关文档