Spring中使用yaml作为配置文件

写定制的时候经常会遇到这样的情况,一些小而繁杂的配置项在数据库中配置太过麻烦,卸载application.properties中又太过臃肿,针对这种情况,我们可以使用yaml作为配置文件,直接在model类中将yaml配置引入即可。具体使用方法如下:

Step1: 创建yaml解析类

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
public class YamlPropertySourceFactory implements PropertySourceFactory {
    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
        Resource classResource = resource.getResource();
        if (classResource.exists()) {
           PropertySource<?> sources = new YamlPropertySourceLoader().load(resource.getResource().getFilename(), classResource,null);
            return sources==null ? new MapPropertySource(name, new HashMap<>()) : sources;
        }
        return new MapPropertySource(name, new HashMap<>());
    }
}

Step2: 设置配置文件

在项目的