java - 使用 YamlMapFactoryBean 通过 PropertySourceFactory 在 Spring Boot 中读取 YAML 属性文件
问题描述
我正在尝试使用使用提供的 YamlMapFactoryBean 解析器的工厂通过 spring boot @PropertySource 机制读取 YAML 配置文件。
工厂的实现如下:
public class YamlPropertySourceFactory implements PropertySourceFactory {
@Override
public PropertySource<?> createPropertySource(String name, EncodedResource encodedResource) {
YamlMapFactoryBean factory = new YamlMapFactoryBean();
factory.setResources(encodedResource.getResource());
Map<String, Object> map = factory.getObject();
return new MapPropertySource(encodedResource.getResource().getDescription(), map);
}
}
YAML 配置文件 (foo.yml) 是:
yaml:
name: foo
aliases:
- abc
- xyz
对应的实体是:
@Configuration
@ConfigurationProperties(prefix = "yaml")
@PropertySource(value = "classpath:foo.yml", factory = YamlPropertySourceFactory.class)
public class YamlFooProperties {
private String name;
private List<String> aliases;
// Getters and Setters...
}
最后,我的测试课是:
@RunWith(SpringRunner.class)
@SpringBootTest
public class YamlFooPropertiesTest {
@Autowired
private YamlFooProperties yamlFooProperties;
@Test
public void whenFactoryProvidedThenYamlPropertiesInjected() {
assertThat(yamlFooProperties.getName()).isEqualTo("foo");
assertThat(yamlFooProperties.getAliases()).containsExactly("abc", "xyz");
}
}
在调试工厂时,我看到 YAML 文件被正确解析并添加到 spring boot 的propertySourceNames
结构中。但是,当以 Autowired 方式从测试中访问它时,所有字段都为空,因此测试失败。
解决方案
推荐阅读
- coq - Coq 引理语句中的定义与命题相等
- java - 无法弄清楚如何让程序检测到我输入了某个字符串并根据该字符串执行某些操作
- r - 如何从 R 中的 lm 打印出设计矩阵?
- r - 如何下载需要在 R 中登录的 csv
- android - How to set a gradient background in a Material Button from Material Components?
- javascript - How to store colors globally so that they are visible in js, css and html?
- python - Python extract tags from string by string array
- php - 使用jquery根据登录状态隐藏和显示页面内容是否安全?(包括登录/注册表单的所有内容)
- jmeter - Problem with a curl parameter in OS Process Sampler
- healthkit - 如何从 HealthKit CDADocumentSampleWithData:'s validationError 中确定 CCD 错误行