【问题标题】:Set spring boot properties via command line argument通过命令行参数设置 Spring Boot 属性
【发布时间】:2020-01-31 09:03:28
【问题描述】:

我有 2 个属性文件:

  • application.yml
  • bootstrap.yml

我为我的应用程序嵌入了 jar 文件,并使用以下命令启动它:java -jar 'jar file path' 我需要用外部位置的文件覆盖属性文件。
试过:-Dspring.config.location=your/config/dir/ 参数,但它不起作用。

您能否告诉我如何用几个属性文件覆盖属性的正确方法?

我的 bootstrap.yml 看起来像:

spring:
  application.name: app_name
  profiles:
    active: local
    include:
  cloud.consul.enabled: false
  main:
    web-application-type: none

---
spring:
  profiles: withconsul
  cloud:
    config.allow-override: true
    consul:
      enabled: true
      host: https://consul.evoil.ru
      port: 443
      config:
        enabled: true
        format: YAML
        fail-fast: true

我应该重命名现有配置文件的属性文件吗?

【问题讨论】:

    标签: java spring-boot properties-file


    【解决方案1】:

    除了spring.config.location之外,您还需要使用spring.config.name

    java -jar 'jar file path' --spring.config.name=external-prop-file-name --spring.config.location=your/config/dir/
    

    https://docs.spring.io/spring-boot/docs/current/reference/html/spring-boot-features.html#boot-features-external-config-application-property-files

    更新:

    如果您想应用两个外部文件的属性(但 bootstrap.yml 中的属性优先于 application.yml 中的属性)然后您需要将 bootstrap.yml 文件重命名为 application-bootstrap.yml 并使用 bootstrap 配置文件启动应用程序:

    java -jar 'jar file path' --spring.profiles.active=bootstrap --spring.config.location=your/config/dir/
    

    在本例中,我省略了 --spring.config.name 参数,因为它的默认值为 application(https://docs.spring.io/spring-boot/docs/current/reference/html/appendix-application-properties.html#core-properties)。

    更新 2:

    如果 withconsul 配置文件已在 application.yml 文件中激活,并且您不想添加新配置文件,则可以将 bootstrap.yml 文件重命名为 application-withconsul。 yml

    【讨论】:

    • 谢谢,如果是2个文件,我应该如何在--spring.config.name=external-prop-file-name中写参数?
    • 我用你所问的例子更新了答案。
    • 我已经更新了问题,请检查我是否理解正确
    猜你喜欢
    • 1970-01-01
    • 2016-04-15
    • 1970-01-01
    • 1970-01-01
    • 2019-01-10
    • 2019-03-04
    • 2018-04-30
    • 2018-04-14
    • 2020-10-29
    相关资源
    最近更新 更多