spring - 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。
基本上我想要一个类型化属性的列表。我究竟做错了什么?
解决方案
一些评论强调了所提供代码的多个问题。
首先,配置属性中的字段不能是最终的,因为 spring 使用 setter 来设置值。其次,@YamlPropertySource
不是 spring 提供的东西,所以在这种情况下不会做任何事情。第三,即使你确实使用了 springPropertySource
注释,很遗憾你不能将它与 yaml 文件一起使用。
无法使用 @PropertySource 注解加载 YAML 文件。
我创建了一个示例项目,该项目使用您提供的代码并进行了修改,使其通过了单元测试。它使用的是 spring boot 2.x 而不是 1.x,但唯一显着的区别应该是测试类中使用的注释。
https://github.com/michaelmcfadyen/spring-boot-config-props-demo
推荐阅读
- r - 删除 sankey 网络中的“未使用”节点
- xaml - 如何在 ItemClick 中为 ListItem 设置动画?
- visual-studio - Visual Studio 和 TFS 中是否有办法查看签出到本地工作区的项目?
- php - 我的 php Post 值无法传输到我的 MySQL 数据库。每当我回显我的值但无法将值插入我的 Mysql Datab 时
- python - 属性错误 Crazyflie
- maven - 为 maven 密码加密生成 settings-security.xml 文件
- java - spring boot - 从 src 外部的文件夹中提供图像
- python - 通过python从.txt文件中的数字数据中分离字符串
- google-bigquery - BigQuery 条件运行总和
- javascript - 尝试在three.js中添加自定义字体