如何将程序参数传递给Spring Boot命令行应用程序?

时间:2020-08-25 08:23:52

标签: java spring-boot maven command-line-arguments

Java程序通常在eclipse上有一个选项可以传递参数: enter image description here

我正在尝试对springboot和maven进行同样的操作,但是没有选择这样做 enter image description here

如何将参数传递给主类?

public static void main(String[] args) {
    // disabled banner, don't want to see the spring logo
    SpringApplication app = new SpringApplication(EnvioTelesapApplication.class);
    app.setBannerMode(Banner.Mode.OFF);

    app.run(args);
}

编辑:

使用-Dspring-boot.run.arguments =“ T111111,SS”将所有参数作为一个参数

1 个答案:

答案 0 :(得分:0)

使用spring boot时,您可能应该利用application.properties文件的优势,并根据需要覆盖它们(包括通过命令行)。 尽管如此,当您将Spring应用程序作为Maven构建而不是Java应用程序运行时,仍然看不到“ arguments”选项卡。在这种情况下,您需要将参数作为Maven目标本身的一部分传递:

  • Spring Boot 1.x:spring-boot:run -Drun.arguments=--spring.main.banner-mode=off,--customArgument=custom
  • Spring Boot 2.x:spring-boot:run -Dspring-boot.run.arguments=--spring.main.banner-mode=off,--customArgument=custom

详细检查春季配置如何工作:https://docs.spring.io/spring-boot/docs/current/reference/html/spring-boot-features.html#boot-features-external-config

修改

一旦定义了属性(在application-properties文件,命令行参数,环境变量等中),就可以通过@Value("${foo}")进行检索,其中foo是属性名称

此外,如果您有兴趣将命令行参数传递给通过jar文件运行的Spring Boot应用程序,则语法为:java -jar myjar.jar --argOne=value --argTwo=value Spring Boot documentation

相关问题