dangsn
2024-06-06 33321f5486fd586fda6fd3f46b7e71754fede28b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
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<PropertySource<?>> 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;
 
    }
}