springboot中通过@PropertySource加载自定义yml文件

使用@PropertySource默认加载的是.xml或者 .properties文件,因为在注解源码默认使用的是DefaultPropertySourceFactory实现处理文件内容,spring
使用ResourcePropertySource从Resource构建Properties传给Spring。
springboot中通过@PropertySource加载自定义yml文件_第1张图片

系统的应用,比如加载自定义的文件,将配置文件内容存储在内存,如下:
springboot中通过@PropertySource加载自定义yml文件_第2张图片

那么加载一个自定义的.yml文件,就需要自定义实现ResourcePropertySource来处理yml文件的类,
springboot中通过@PropertySource加载自定义yml文件_第3张图片
springboot中通过@PropertySource加载自定义yml文件_第4张图片

public class YamlPropertySourceFactory implements PropertySourceFactory {
    @Override
    public PropertySource createPropertySource(String name, EncodedResource resource) throws IOException {
        Properties propertiesFromYaml = loadYamlIntoProperties(resource);
        String sourceName = name != null ? name : resource.getResource().getFilename();
        return new PropertiesPropertySource(sourceName, propertiesFromYaml);
    }

    private Properties loadYamlIntoProperties(EncodedResource resource) throws FileNotFoundException {
        try {
            YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
            factory.setResources(resource.getResource());
            factory.afterPropertiesSet();
            return factory.getObject();
        } catch (IllegalStateException e) {
            // for ignoreResourceNotFound
            Throwable cause = e.getCause();
            if (cause instanceof FileNotFoundException)
                throw (FileNotFoundException) e.getCause();
            throw e;
        }
    }
}

你可能感兴趣的:(spring,springboot)