我正在关注Spring Boot 24.8.3 Merging Complex Types文档的24. Externalized Configuration部分。
我有这个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。
基本上我想要一个类型化属性的列表。我在做什么错了?
答案 0 :(得分:0)
一些评论突出显示了所提供代码的多个问题。
首先,由于spring使用setter来设置值,所以配置属性中的字段不能是final。
其次,@YamlPropertySource
不是spring提供的,因此在这种情况下不会做任何事情。
第三,不幸的是,即使您确实使用了弹簧PropertySource
注释,也无法将其用于yaml文件。
无法使用@PropertySource批注来加载YAML文件。
我创建了一个示例项目,该示例项目使用您提供的代码并进行了修改,以便通过单元测试。它使用的是Spring Boot 2.x而不是1.x,但是唯一的区别应该是测试类中使用的注释。
https://github.com/michaelmcfadyen/spring-boot-config-props-demo