springboot源码分析8-环境属性构造过程(下)

来源:互联网 发布:js防水涂料做法 编辑:程序博客网 时间:2024/06/06 20:09

上一文springboot源码分析7-环境属性构造过程(上)中详细讲解了springboot环境的各种初始化操作。本文我们继续探讨一下环境的一些知识点。

首先,我们看一下抽象基类AbstractEnvironment。该类中的构造函数如下:

1 private final MutablePropertySources propertySources = new MutablePropertySources(this.logger);

2 public AbstractEnvironment() {

3 customizePropertySources(this.propertySources);

4 }

该类的构造函数中会直接调用customizePropertySources方法,customizePropertySources方法是个空的方法,因此最终各种子类一定回去重写该方法的,这个我们上个章节详细地说明过。这里重点看下customizePropertySources方法中的入参propertySourcespropertySourcesAbstractEnvironment类中已经实例化了。而且是个对象因此是引用类型,因此所有的自类都是可以拿到这个对象的引用的。propertySources为MutablePropertySources类型。MutablePropertySources 我们需要重点的讲解一下。

1.1. MutablePropertySources

 MutablePropertySources类的层级结构图如下所示:

 

 

MutablePropertySources类实现了PropertySources接口。该类中持有了所有的一个propertySourceList集合。propertySourceList集合中的元素类型是PropertySourcePropertySource类的作用,前面的章节也详细讲解了,因此这里不再赘述。MutablePropertySources中所定义的大部分想法均是对propertySourceList集合进行操作,比如在该集合的头部添加元元素、尾部添加元素、在指定的元素之后添加元素。该类的核心方法如下所示:

 

 

这里以addLast方法为例进行说明:

1 public void addLast(PropertySource<?> propertySource) {

2 removeIfPresent(propertySource);

3 this.propertySourceList.add(propertySource);

4 }

首先调用了removeIfPresent方法,然后直接将propertySource添加到propertySourceList集合中,removeIfPresent方法实现逻辑如下:

1 protected void removeIfPresent(PropertySource<?> propertySource) {

2 this.propertySourceList.remove(propertySource);

3 }

逻辑非常的简单,直接将propertySourcepropertySourceList集合中进行移除。

在这里简单补充一点:所有的PropertySource以及子类均存储在propertySourceList集合中,而该集合是一个List类型,List是有顺序的,因此最终的元素添加顺序,决定了元素的最终遍历查找顺序,这里一定要注意。关于propertySourceList集合的元素添加方式,如下所示:

1 protected void customizePropertySources(MutablePropertySources propertySources) {

2 propertySources.addLast(new MapPropertySource(SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME, getSystemProperties()));

3 propertySources.addLast(new SystemEnvironmentPropertySource(SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, getSystemEnvironment()));

4 }

后续文章,我们重点讲解各种PropertySource以及子类的使用。


欢迎关注我的微信公众号,第一时间获得博客更新提醒,以及更多成体系的Java相关原创技术干货。 
扫一扫下方二维码或者长按识别二维码,即可关注。
 



阅读全文
0 0