java—使用yamlmapfactorybean通过propertysourcefactory在spring引导中读取yaml属性文件

oymdgrw7  于 2021-07-23  发布在  Java
关注(0)|答案(0)|浏览(345)

我试图通过spring boot@propertysource机制读取yaml配置文件,使用的工厂使用提供的yamlmapfactorybean解析器。
工厂实施情况如下:

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文件被正确解析并添加到springboot的 propertySourceNames 结构。但是,当以自动连线方式从测试访问它时,所有字段都为空,因此测试失败。

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题