【问题标题】:Spring - how to override internal config file with external fileSpring - 如何用外部文件覆盖内部配置文件
【发布时间】:2016-11-23 08:59:31
【问题描述】:

在我的 spring 项目中,我有两个具有相同属性的不同 conf 文件。

其中一个在外部目录中,而另一个在我项目的资源中。

我希望外部文件的属性覆盖内部值(如果它们存在于外部文件中)。

在我的配置类中,我使用 PropertySource 注释设置文件:

@PropertySources(
{ @PropertySource("file:${HOME}/conf/application.properties"),  
  @PropertySource("classpath:/data.properties")  
})

【问题讨论】:

    标签: java spring spring-boot


    【解决方案1】:

    默认情况下,PropertySource 的工作方式如下: - 读取第一个属性文件 - 读取第二个 (...) 属性文件 - 如果它包含已经给定的键,它将被覆盖。

    在这里查看:http://javapapers.com/spring/spring-properties-with-propertysource-annotation/

    如果您想将它与 XML 一起使用,请查看此答案:What is property resolution order in Spring property placeholder configurer with multiple locations?

    【讨论】:

      【解决方案2】:

      假设你正在使用 spring-boot 并且有胖的可执行 jar, 您可以使用外部命令行参数覆盖内部配置文件属性,如下所示

      java -jar your-executable-fat-jar.jar --spring.config.name=external-prop-file-name --spring.config.location=classpath:/application.properties,file://<external-config-file-parent-dir-path-NOT-EXTERNAL-CONFIG-FILE-PATH>
      

      在哪里

      spring.config.name - external config file name
      spring.config.location - Locations to look for configuration files
      

      注意:以上配置,spring-boot会在spring.config.location传入的外部目录中寻找external-prop-file-name.properties

      【讨论】:

        【解决方案3】:

        声明文件的顺序很重要。如果在两个或多个文件中定义了相同的键,则与最后声明的文件中的键关联的值将覆盖任何先前的值。

        来自spring docs:

        如果给定的属性键存在于多个 .properties 文件中,则处理的最后一个 @PropertySource 注释将“获胜”并覆盖。

        所以只需将@PropertySource("file:${HOME}/conf/application.properties") 与@PropertySource("classpath:/data.properties") 交换

        示例: @PropertySources({@PropertySource("classpath:/data.properties"),@PropertySource("file:${HOME}/conf/application.properties")})

        【讨论】:

        • 像魅力一样工作。非常感谢
        猜你喜欢
        • 1970-01-01
        • 2020-11-09
        • 2021-11-02
        • 1970-01-01
        • 2019-09-05
        • 2022-01-18
        • 1970-01-01
        • 2017-12-09
        • 2016-08-19
        相关资源
        最近更新 更多