【问题标题】:Spring Boot Externalize properties from within application.propertiesSpring Boot 从 application.properties 中外部化属性
【发布时间】:2021-05-17 00:33:10
【问题描述】:

我想将我的属性源位置设置为从 application.propoerties 本身指向外部目录。 我知道传递命令行参数如下所示。

java -jar myApp.jar --spring.config.location=/Users/tony/Desktop/override.properties

但我想从应用程序本身设置此路径,而不是传递命令行参数。我尝试将 spring.config.location=/Users/tony/Desktop/override.properties 添加到我的 application.properties 但它不起作用。

我该怎么做?

【问题讨论】:

    标签: spring-boot config spring-boot-actuator properties-file


    【解决方案1】:

    spring.config.locationspring.config.additional-location 仅在设置为环境变量、系统属性或命令行参数时才有用。

    application.properties 文件中指定要直接加载的其他配置文件的最佳方法是像这样设置spring.config.import 属性:

    spring.config.import=file:/Users/tony/Desktop/override.properties

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

    【讨论】:

      【解决方案2】:

      您可以尝试在调用SpringApplication.run() 的主类中添加以下注释:

      @PropertySource("/Users/tony/Desktop/override.properties")

      在运行 SpringBoot 应用程序时,它应该从那里获取属性。在 pom.xml 中使用 build - resources - resource - excludes - excludesrc/main/resources 中排除 application.properties 将有助于确保打包的 jar 不包含 applcation.properties 和将强制 Spring Boot 从 @PropertySource 中指定的路径中获取它

      <build>
          <resources>
              <resource>
                  <directory>src/main/resources</directory>
                  <filtering>true</filtering>
                  <excludes>
                      <exclude>**/application.properties</exclude>
                  </excludes>
              </resource>
          </resources>
      </build>
      

      但请记住,通过这种方式,您正在创建属性文件与应用程序的紧密耦合。如果您将其保留为运行时参数,它将具有足够的灵活性以在其他地方运行并且维护也将更容易。

      【讨论】:

      • 感谢 Kavitha 的深入回答!这完成了工作......是的,我知道这会在罐子中产生紧密耦合。我会接受您的建议并改用运行时参数。谢谢!
      • 顺便说一句,你是怎么发现的?我试着在这里查看 spring 文档:[link] (docs.spring.io/spring-boot/docs/1.0.1.RELEASE/reference/html/…)。按照给定的顺序,我应该也可以在属性文件中使用spring.config.location=/Users/tony/Desktop/override.properties,因为我没有使用任何具有更高优先级的东西。
      • 很高兴您发现它很有用。我从here 开始的一些研究中发现了这一点:)
      猜你喜欢
      • 2020-06-22
      • 2020-03-18
      • 2018-02-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-25
      • 2015-11-06
      • 2017-09-19
      相关资源
      最近更新 更多