首页 > 解决方案 > Spring Boot Yaml 配置:类型化属性列表

问题描述

我正在关注Spring Boot 的24. 外部化配置文档的24.8.3 合并复杂类型部分。我有这个文件:config.yaml

acme:
  list:
    - name: my name
      description: my description
    - name: another name
      description: another description

属性文件如下所示:

@ConfigurationProperties("acme")
@YamlPropertySource(value = { "classpath:/config.yaml" })
public class AcmeProperties {

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

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

MyPojo班级:

public class MyPojo {
    private String name;
    private String description;

    public MyPojo(String name, String description) {
        this.name = name;
        this.description = description;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }
}

失败的测试如下所示:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { AcmeProperties.class })
public class AcmePropertiesTest {

    @Autowired
    private AcmeProperties properties;

    @Test
    public void getOpScoringClusters() {
        Assert.assertEquals(2, properties.getList().size()); // FAIL!
    }
}

Spring Boot 版本 1.5.6。

基本上我想要一个类型化属性的列表。我究竟做错了什么?

标签: springspring-boot

解决方案


一些评论强调了所提供代码的多个问题。

首先,配置属性中的字段不能是最终的,因为 spring 使用 setter 来设置值。其次,@YamlPropertySource不是 spring 提供的东西,所以在这种情况下不会做任何事情。第三,即使你确实使用了 springPropertySource注释,很遗憾你不能将它与 yaml 文件一起使用。

无法使用 @PropertySource 注解加载 YAML 文件。

我创建了一个示例项目,该项目使用您提供的代码并进行了修改,使其通过了单元测试。它使用的是 spring boot 2.x 而不是 1.x,但唯一显着的区别应该是测试类中使用的注释。

https://github.com/michaelmcfadyen/spring-boot-config-props-demo


推荐阅读