package com.vci.starter.web.yml; import org.springframework.boot.env.YamlPropertySourceLoader; import org.springframework.core.env.PropertySource; import org.springframework.core.io.Resource; import org.springframework.core.io.support.EncodedResource; import org.springframework.core.io.support.PropertySourceFactory; import org.springframework.util.CollectionUtils; import java.io.IOException; import java.util.List; /** * 读取自定义的yml文件 * @author weidy * @date 2020/3/13 */ public class YamlPropertySourceFactory implements PropertySourceFactory { /** * 创建yaml的工厂资源 * @param name 名称 * @param resource 资源集合 * @return 存在的时候返回propertySource * @throws IOException 读取文件错误会抛出异常 */ @Override public PropertySource createPropertySource(String name, EncodedResource resource) throws IOException { //调用yaml List> sourceList = name != null ? new YamlPropertySourceLoader().load( name, resource.getResource()) : new YamlPropertySourceLoader().load( getNameForResource(resource.getResource()), resource.getResource()); if(!CollectionUtils.isEmpty(sourceList)){ return sourceList.get(0); } return null; } /** * 获取资源的名称 * @param resource 资源对象 * @return 资源名称 */ private static String getNameForResource(Resource resource) { String name = resource.getDescription(); if (!org.springframework.util.StringUtils.hasText(name)) { name = resource.getClass().getSimpleName() + "@" + System.identityHashCode(resource); } return name; } }