You need to enable JavaScript to run this app. Spring Boot @PropertySource结合YamlMapFactoryBean读YAML配置注入失败
优惠活动
大模型
产品
解决方案
定价
更多

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");
        }
    }
    

实际运行异常

调试链路可以确认两个符合预期的环节:

  1. 自定义工厂类已经正确解析出YAML的全部内容
  2. 解析生成的属性源已经成功加入Spring Boot的propertySourceNames结构

但最终配置绑定逻辑完全失效:自动注入的YamlFooProperties实例所有字段值均为null,直接导致测试断言失败。

内容的提问来源于stack exchange,提问作者KidCrippler

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.04 21:06:02