首页 > 解决方案 > 使用 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 方式从测试中访问它时,所有字段都为空,因此测试失败。

标签: javaspringspring-bootyamlproperties-file

解决方案


推荐阅读