SpringBoot之浅析配置项解析(三)

我们接着上一篇的文章继续分析。我们来看这一段代码:

//在上一篇文章中我们分析了getSearchNames()这个方法,这个方法默认返回 只有一个元素 application的List 
for (String name : getSearchNames()) {
    //我们分析的重点  profile 为null
    load(location, name, profile);
}
String group = "profile=" + (profile == null ? "" : profile);
//这里的name是application 所以不会走这里
if (!StringUtils.hasText(name)) {
    // Try to load directly from the location
    loadIntoGroup(group, location, profile);
}
else {
    // Search for a file with the given name
    //获取所有的扩展名 1)
    for (String ext : this.propertiesLoader.getAllFileExtensions()) {
    //我们的profile为null 所以这里的逻辑可以先剥离出去不看 直接看下面的汉字的部分
    if (profile != null) {
        // Try the profile-specific file
        loadIntoGroup(group, location + name + "-" + profile + "." + ext,
                    null);
        for (Profile processedProfile : this.processedProfiles) {
            if (processedProfile != null) {
                loadIntoGroup(group, location + name + "-"
                            + processedProfile + "." + ext, profile);
            }
        }
        // Sometimes people put "spring.profiles: dev" in
        // application-dev.yml (gh-340). Arguably we should try and error
        // out on that, but we can be kind and load it anyway.
        loadIntoGroup(group, location + name + "-" + profile + "." + ext,
                        profile);
    }
        // Also try the profile-specific section (if any) of the normal file
        //主要调用方法 group : profile=   profile:null
        loadIntoGroup(group, location + name + "." + ext,  profile);
    }
}

我们先来看1)的代码:this.propertiesLoader.getAllFileExtensions()这一句。

    public Set<String> getAllFileExtensions() {
        Set<String> fileExtensions = new LinkedHashSet<String>();
        //循环this.loaders   1)
        for (PropertySourceLoader loader : this.loaders) {
            //将得到的 扩展名 放到 Set中  这是一个 LinkedHashSet 2)
            fileExtensions.addAll(Arrays.asList(loader.getFileExtensions()));
        }
        return fileExtensions;
    }

在代码1)处 this.loaders是什么呢?在ConfigFileApplicationListener.Loader#load()这个方法中有这样一段代码:

this.propertiesLoader = new PropertySourcesLoader();
    public PropertySourcesLoader() {
        //这里创建一个MutablePropertySources 赋给了PropertySourcesLoader中的 propertySources
        this(new MutablePropertySources());
    }
    public PropertySourcesLoader(MutablePropertySources propertySources) {
        Assert.notNull(propertySources, "PropertySources must not be null");
        this.propertySources = propertySources;
        //这一段代码看着就很眼熟了吧 说过很多次了 
        //在spring.factories中的值为:org.springframework.boot.env.PropertiesPropertySourceLoader 
        //和 '  org.springframework.boot.env.YamlPropertySourceLoader
        //这两个属性资源loader 一个适用于 properties 一个适用于 yml(或者yaml)
        this.loaders = SpringFactoriesLoader.loadFactories(PropertySourceLoader.class,
                getClass().getClassLoader());
    }

所以1处的this.loaders 是 元素为 PropertiesPropertySourceLoader 和YamlPropertySourceLoader的List。2)处的loader.getFileExtensions()的代码分别如下:

    public String[] getFileExtensions() {
        //properties和xml后缀
        return new String[] { "properties", "xml" };
    }
    public String[] getFileExtensions() {
        //yml和yaml后缀
        return new String[] { "yml", "yaml" };
    }

所以getAllFileExtensions() 得到的扩展名为含有 “properties”, “xml” ,”yml”, “yaml” 这个四个元素的一个集合。所以我们接着上一章简化的代码,在这里进一步的简化代码为:

List<String> listString = Arrays.asList("file:./config/,file:./,classpath:/config/,classpath:/".split(","));
List<String> listName = Arrays.asList("application");
List<String> fileExtensions = Arrays.asList("properties","xml","yml","yaml");
for (String location : listString) {
     for(String name : listName){
        for(String ext : fileExtensions){
            loadIntoGroup(group, location + name + "." + ext, profile);
        }
    }
}

看到上面的代码,读者应该明白SpringBoot加载的配置文件的位置和文件类型了吧?我们继续到loadIntoGroup看一下它的代码:

private PropertySource<?> loadIntoGroup(String identifier, String location,
        Profile profile) {
    try {
        return doLoadIntoGroup(identifier, location, profile);
    }
}
//去掉了无用的代码
private PropertySource<?> doLoadIntoGroup(String identifier, String location,
            Profile profile) throws IOException {
    //从不同的地方进行资源文件的加载  有兴趣的同学可以看一下Spring是怎么适配不同位置的资源的加载的 不再多说
    //可以参考一下这里:[Spring学习之资源管理器(Resource)](http://blog.csdn.net/zknxx/article/details/72383848)
    Resource resource = this.resourceLoader.getResource(location);
    PropertySource<?> propertySource = null;
    if (resource != null && resource.exists()) {    
        String name = "applicationConfig: [" + location + "]";
        String group = "applicationConfig: [" + identifier + "]";
        //加载解析资源文件 
        propertySource = this.propertiesLoader.load(resource, group, name,
                (profile == null ? null : profile.getName()));
        if (propertySource != null) {
            //Profile的处理
            handleProfileProperties(propertySource);
        }
    }
}

org.springframework.boot.env.PropertySourcesLoader#load

    public PropertySource<?> load(Resource resource, String group, String name,
            String profile) throws IOException {
        //判断该资源是不是文件类型 这样的代码 在写自己的框架的时候是可以借鉴直接使用的
        if (isFile(resource)) {
            String sourceName = generatePropertySourceName(name, profile);
            for (PropertySourceLoader loader : this.loaders) {
                //这里判断能不能加载 文件 是根据 每个loader 对应的扩展类型 进行匹配的 是不是相应的 扩展名 结尾
                //PropertiesPropertySourceLoader  "properties", "xml" 
                //YamlPropertySourceLoader   "yml", "yaml"  
                if (canLoadFileExtension(loader, resource)) {
                    //对应 properties和xml文件的加载 大家都比较熟悉一点,感兴趣的可以看一下对于yaml文件加载过程
                    //PropertiesPropertySourceLoader加载的文件封装为了PropertiesPropertySource
                    //YamlPropertySourceLoader加载的文件封装为了MapPropertySource
                    PropertySource<?> specific = loader.load(sourceName, resource,
                            profile);
                    //这一段代码有必要说明一下
                    addPropertySource(group, specific, profile);
                    return specific;
                }
            }
        }
        return null;
    }
    private void addPropertySource(String basename, PropertySource<?> source,
            String profile) {
        //如果source为null 直接返回
        if (source == null) {
            return;
        }
        //如果basename为null将resource添加到最后
        if (basename == null) {
            this.propertySources.addLast(source);
            return;
        }
        //根据名字获取EnumerableCompositePropertySource
        EnumerableCompositePropertySource group = getGeneric(basename);
        //将前面得到的source放入到EnumerableCompositePropertySource中
        //EnumerableCompositePropertySource 内部维护了一个LinkedHashSet
        group.add(source);
        //如果之前有这个name的话,则进行替换的工作
        if (this.propertySources.contains(group.getName())) {
            this.propertySources.replace(group.getName(), group);
        }
        else {
            //如果之前没有这个name的话,则插入到头部
            this.propertySources.addFirst(group);
        }
    }

如果我们的配置文件是这样的:
location
那么我们最终得到的EnumerableCompositePropertySource 是什么样的呢?
EnumerableCompositePropertySource
注意了!!!注意了!!!是properties在前,yml在后说明properties的优先级比yml高!!!!!
我们再来看一下这一段的代码,在org.springframework.boot.context.config.ConfigFileApplicationListener.Loader#load()中

//如果你一直跟着我说的在对着源码进行分析的话,那么对于this.propertiesLoader.getPropertySources()这个方法得到的PropertySources一定不陌生。它就是在PropertySourcesLoader中创建的MutablePropertySources,它的元素为上面图中的元素
addConfigurationProperties(this.propertiesLoader.getPropertySources());
private void addConfigurationProperties(MutablePropertySources sources) {
    //将之前得到的MutablePropertySources中的PropertySource转换为List<PropertySource<?>>
    List<PropertySource<?>> reorderedSources = new ArrayList<PropertySource<?>>();
    for (PropertySource<?> item : sources) {
        reorderedSources.add(item);
    }
    //将上面得到的List<PropertySource<?>> 包装为ConfigurationPropertySources 
    //它的name为applicationConfigurationProperties
    addConfigurationProperties(new ConfigurationPropertySources(reorderedSources));
}
private void addConfigurationProperties(ConfigurationPropertySources configurationSources) {
    //获取环境变量中的MutablePropertySources 这个MutablePropertySources包含之前得到的 命令行的PropertySource、ServletConfig的、ServletContext、虚拟机的、系统的PropertySource
    MutablePropertySources existingSources = this.environment.getPropertySources();
    //如果有defaultProperties
    if (existingSources.contains(DEFAULT_PROPERTIES)) {
        //则将之前得到的ConfigurationPropertySources插入到defaultProperties的前面 我们之前分析中得知 defaultProperties元素的位置位于最后
        existingSources.addBefore(DEFAULT_PROPERTIES, configurationSources);
    }
    else {
        //将将之前得到的ConfigurationPropertySources插入到最后
            existingSources.addLast(configurationSources);
        }
    }
}

讲过上面的分析,我们可得到一个不同的配置项在环境变量中所处的一个位置情况:commandLineArgs、servletConfigInitParams 、servletContextInitParams 、jndiProperties 、systemProperties 、systemEnvironment、random、applicationConfigurationProperties、defaultProperties。 applicationConfigurationProperties中元素的位置顺序 file:./config/、file:./、classpath:/config/、classpath:/,其中properties后缀的文件在前,yml在后。

猜你喜欢

转载自blog.csdn.net/zknxx/article/details/79028922