PropertySources 中各种源的优先级

Priority of Various Sources in PropertySources

Spring 为自 4.0 以来标记为 @Configuration 的所有 类 引入了新注释 @PropertySources。它采用不同的 @PropertySource 作为参数。

@PropertySources({
    @PropertySource("classpath:application.properties"), @PropertySource("file:/tmp/application.properties")})

我感兴趣的是在多个属性文件中存在的相同键的值发生冲突时的排序。我还没有看到任何与此相关的指定排序的文档。我试了很多次,发现后面提到的 PropertySource 覆盖了前面提到的 PropertySource 中存在的值。但是,如何确定呢?

@PropertySources 的文档没有说明相同 属性 存在于多个 @PropertySource 文件中的情况。

但是,@PropertySource 的文档说明如下:

In cases where a given property key exists in more than one .properties file, the last @PropertySource annotation processed will 'win' and override

由于@PropertySources 中的@PropertySource 声明实际上是一个table,因此可以相当安全地假设最后声明的@PropertySource 覆盖了之前的声明。这与我所做的测试以及 blog post.

一致

但是,正如问题中提到的,文档中没有明确说明。因此,这种行为将来可能 "accidentally" 会发生变化。

根据我的测试,@PropertySources 注释中的 @PropertySource 注释似乎按照它们出现的顺序进行处理,但是如果您 ,它们将打印在倒序。

注解:

@Configuration
@PropertySources({
  @PropertySource(value = "classpath:application.global.properties"),
  @PropertySource(
      value = "classpath:application.client-specific.properties",
      ignoreResourceNotFound = true),
  @PropertySource(
      value = "file:/etc/omnia/application.client-specific.properties",
      ignoreResourceNotFound = true),
  @PropertySource(value = "classpath:application.test.properties", ignoreResourceNotFound = true)
})

以及日志输出:

Loading @PropertySource: 'configurationProperties'
Loading @PropertySource: 'servletConfigInitParams'
Loading @PropertySource: 'servletContextInitParams'
Loading @PropertySource: 'systemProperties'
Loading @PropertySource: 'systemEnvironment'
Loading @PropertySource: 'random'
Loading @PropertySource: 'URL [file:/etc/omnia/application.client-specific.properties]'
Loading @PropertySource: 'class path resource [application.global.properties]'

HL'REB 是对的。 "Win" 来自最后一个属性文件的参数。但是,application.properties 会覆盖所有值。检查 SPRING 5.1.6.