24.6.5 合并YAML列表

正如上面看到的,所有YAML最终都转换为properties,在通过一个profile覆盖"list"属性时这个过程可能不够直观(counter intuitive)。例如,假设有一个MyPojo对象,默认它的namedescription属性都为null,下面我们将从FooProperties暴露一个MyPojo对象列表(list):

@ConfigurationProperties("foo")
public class FooProperties {

    private final List<MyPojo> list = new ArrayList<>();

    public List<MyPojo> getList() {
        return this.list;
    }

}

考虑如下配置:

foo:
  list:
    - name: my name
      description: my description
---
spring:
  profiles: dev
foo:
  list:
    - name: my another name

如果dev profile没有激活,FooProperties.list将包括一个如上述定义的MyPojo实体,即使dev生效,该list仍旧只包含一个实体(name值为my another namedescription值为null)。此配置不会向该列表添加第二个MyPojo实例,也不会对该项进行合并。

当一个集合定义在多个profiles时,只使用优先级最高的:

foo:
  list:
    - name: my name
      description: my description
    - name: another name
      description: another description
---
spring:
  profiles: dev
foo:
  list:
     - name: my another name

在以上示例中,如果dev profile激活,FooProperties.list将包含一个MyPojo实体(name值为my another namedescription值为null)。

Last updated