【问题标题】:Spring boot classpath configuration files overrides external application.propertiesSpring Boot 类路径配置文件覆盖外部 application.properties
【发布时间】:2020-11-09 16:20:21
【问题描述】:

我想让 Spring 加载一个外部配置文件(如果存在),否则使用 src/main/resources 中提供的一次。

当前设置:

src/main/resources/application.properties
src/main/resources/application-dev.properties
src/main/resources/application-prod.properties

/this/is/an/external/dir/application-dev.properties

类似于https://stackoverflow.com/a/27776123/5126654我添加了如下注解:

@EnableFeignClients
@SpringBootApplication
@EnableEncryptableProperties
@PropertySources({ //
    @PropertySource("classpath:application.properties"), //
    @PropertySource(value = "file:${external.config}", ignoreResourceNotFound = true) //
})
public class Application extends SpringBootServletInitializer {

   // ....
}

并且在我的 application.properties 中有以下条目:

external.config=/this/is/an/external/dir/application-dev.properties

我还可以看到外部配置文件被拾取。我遇到的问题是类路径属性文件中的每个条目都会覆盖外部条目。 IE。而不是从 /this/is/an/external/dir/application-dev.properties 条目来自 src/main/resources/application-dev.properties 被占用。

如何修改我的代码以使外部文件覆盖类路径文件的条目?

【问题讨论】:

    标签: java spring spring-boot


    【解决方案1】:

    只需更改导入顺序即可。 比如:

    <context:property-placeholder file-encoding="UTF-8"
                                location="${YOUR_CUSTOM_PATH}/global.properties ,
                                          ${YOUR_CUSTOM_PATH}/local.properties" ignore-unresolvable="true"/>
    

    @PropertySource(value = {"classpath:global.properties" , "local.properties"},ignoreResourceNotFound = true)
    

    在这种情况下,local.properties 会覆盖 global.properties 的属性

    【讨论】:

    【解决方案2】:

    由于您只希望外部配置用于开发,因此您也可以考虑在项目的 IDE 运行配置中将外部属性源设置为命令行参数。

    --spring.config.location=/this/is/an/external/dir/application-dev.properties
    

    以上述方式指定的属性源会覆盖类路径中存在的 application.properties。

    【讨论】:

      【解决方案3】:

      我想让 Spring 加载一个外部配置文件(如果存在),否则使用 src/main/resources 中提供的一次。

      这是 Spring Boot 的默认行为。所以你只需要正确启用它。

      首先,删除下一​​个注释,它们可能会破坏/覆盖默认机制:

      @PropertySources({ //
          @PropertySource("classpath:application.properties"), //
          @PropertySource(value = "file:${external.config}", ignoreResourceNotFound = true) //
      })
      

      然后将文件的位置指定为命令行参数:

      java -jar myapp.jar --spring.config.additional-location=/this/is/an/external/dir/
      

      更多信息在这里:

      然后将您的配置重命名为 application.properties 或通过另一个环境变量指定您的 dev 配置文件(文件名中的后缀):

      -Dspring-boot.run.profiles=dev
      

      相关问题:Setting active profile and config location from command line in spring boot

      【讨论】:

        猜你喜欢
        • 2020-06-22
        • 2021-11-02
        • 1970-01-01
        • 2018-12-19
        • 1970-01-01
        • 1970-01-01
        • 2019-09-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多