关于@PropertySource注解对于yml的支持

时间:2019-10-17
本文章向大家介绍关于@PropertySource注解对于yml的支持,主要包括关于@PropertySource注解对于yml的支持使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

@PropertySource只对properties文件可以进行加载,但对于yml或者yaml不能支持。
追寻源码。

public class DefaultPropertySourceFactory implements PropertySourceFactory {
    public DefaultPropertySourceFactory() {
    }

    public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
        return name != null ? new ResourcePropertySource(name, resource) : new ResourcePropertySource(resource);
    }
}

我们只需要继承DefaultPropertySourceFactory类并修改就可以了。

public class YamlConfigFactory extends DefaultPropertySourceFactory {

    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
        String sourceName = name != null ? name : resource.getResource().getFilename();
        if (!resource.getResource().exists()) {
            return new PropertiesPropertySource(sourceName, new Properties());
        } else if (sourceName.endsWith(".yml") || sourceName.endsWith(".yaml")) {
            Properties propertiesFromYaml = loadYml(resource);
            return new PropertiesPropertySource(sourceName, propertiesFromYaml);
        } else {
            return super.createPropertySource(name, resource);
        }
    }

    private Properties loadYml(EncodedResource resource) throws IOException {
        YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
        factory.setResources(resource.getResource());
        factory.afterPropertiesSet();
        return factory.getObject();
    }
}

使用yml注入属性值

@PropertySource(value = {"classpath:dog.yml"},factory = YamlConfigFactory.class)
@Component
@ConfigurationProperties(prefix = "dog")
public class Dog {

    private String name ;
    private String age ;

原文地址:https://www.cnblogs.com/dmxk/p/11692004.html