Spring Boot @PropertySource结合YamlMapFactoryBean读YAML配置注入失败
Spring Boot 自定义YAML配置绑定全为null问题
现有实现方案
开发者尝试基于@PropertySource机制读取自定义YAML配置,全程实现逻辑如下:
- 自定义
YamlPropertySourceFactory实现PropertySourceFactory接口,核心是借助YamlMapFactoryBean完成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); } } - 待加载的
classpath:foo.yml配置文件内容:yaml: name: foo aliases: - abc - xyz - 配置绑定类
YamlFooProperties上叠加标注三个注解:@Configuration注册为Spring容器Bean@ConfigurationProperties(prefix = "yaml")绑定yaml前缀下的配置项@PropertySource(value = "classpath:foo.yml", factory = YamlPropertySourceFactory.class)指定用自定义工厂加载YAML配置
类内定义name字符串字段、aliases字符串列表字段,配套实现了对应getter/setter方法,核心结构:
@Configuration @ConfigurationProperties(prefix = "yaml") @PropertySource(value = "classpath:foo.yml", factory = YamlPropertySourceFactory.class) public class YamlFooProperties { private String name; private List<String> aliases; // 省略getter/setter方法 } - 配套测试类通过SpringRunner驱动
@SpringBootTest测试环境,自动注入YamlFooProperties实例,断言name值为foo、aliases精确包含abc、xyz两个元素,核心测试代码:@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结构
但最终配置绑定逻辑完全失效:自动注入的YamlFooProperties实例所有字段值均为null,直接导致测试断言失败。
内容的提问来源于stack exchange,提问作者KidCrippler
相关产品推荐
相关产品推荐

