从SpringBoot源码分析 配置文件的加载原理和优先级
server.port: 8888
spring.profiles.active: dev
spring.think: hello
-Dserver.port=5555
如下图:

Tomcat started on port(s): 5555 (http) with context path ''
同时在application.yml 和 启动参数(VM options)中设置 server.port, 最终采用了 启动参数 中的值。
#ApplicationConfigLoadFlow.java
public static void main(String[] args) {
SpringApplication.run(ApplicationConfigLoadFlow.class, args);
}
#SpringApplication.java
return run(new Class<?>[] { primarySource }, args)
#SpringApplication.java
return new SpringApplication(primarySources).run(args);
#SpringApplication.java
public ConfigurableApplicationContext run(String... args) {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
ConfigurableApplicationContext context = null;
Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();
configureHeadlessProperty();
SpringApplicationRunListeners listeners = getRunListeners(args);
listeners.starting();
try {
ApplicationArguments applicationArguments = new DefaultApplicationArguments(
args);
//跟入
ConfigurableEnvironment environment = prepareEnvironment(listeners,
applicationArguments);
configureIgnoreBeanInfo(environment);
configureIgnoreBeanInfo(environment);
进入public ConfigurableApplicationContext run(String... args) 方法后,我们重点看 prepareEnvironment这个方法。

#SpringApplication.java
private ConfigurableEnvironment prepareEnvironment(
SpringApplicationRunListeners listeners,
ApplicationArguments applicationArguments) {
// Create and configure the environment
//跟入
ConfigurableEnvironment environment = getOrCreateEnvironment();
configureEnvironment(environment, applicationArguments.getSourceArgs());
同样的套路,通过debug发现实在getOrCreateEnvironment方法执行后得到server.port的值
#SpringApplication.java
private ConfigurableEnvironment getOrCreateEnvironment() {
if (this.environment != null) {
return this.environment;
}
if (this.webApplicationType == WebApplicationType.SERVLET) {
//跟入
return new StandardServletEnvironment();
}
虚拟机启动参数的加载 是在StandardServletEnvironment 的实例化过程中完成的。

#AbstractEnvironment.java
public AbstractEnvironment() {
//跟入
customizePropertySources(this.propertySources);
if (logger.isDebugEnabled()) {
logger.debug("Initialized " + getClass().getSimpleName() + " with PropertySources " + this.propertySources);
}
}
实体化的过程中回过头来调用了子类StandardServletEnvironment的customizePropertySources方法
#StandardServletEnvironment.java
protected void customizePropertySources(MutablePropertySources propertySources) {
propertySources.addLast(new StubPropertySource(SERVLET_CONFIG_PROPERTY_SOURCE_NAME));
propertySources.addLast(new StubPropertySource(SERVLET_CONTEXT_PROPERTY_SOURCE_NAME));
if (JndiLocatorDelegate.isDefaultJndiEnvironmentAvailable()) {
propertySources.addLast(new JndiPropertySource(JNDI_PROPERTY_SOURCE_NAME));
}
//跟入
super.customizePropertySources(propertySources);
}
又调用了父类StandardEnvironment的customizePropertySources方法
#StandardEnvironment.java
protected void customizePropertySources(MutablePropertySources propertySources) {
//跟入
propertySources.addLast(new MapPropertySource(SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME, getSystemProperties()));
propertySources.addLast(new SystemEnvironmentPropertySource(SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, getSystemEnvironment()));
}

#AbstractEnvironment.java
public Map<String, Object> getSystemProperties() {
try {
//跟入
return (Map) System.getProperties();
#System.java
public static Properties getProperties() {
SecurityManager sm = getSecurityManager();
if (sm != null) {
sm.checkPropertiesAccess();
} return props;
我们搜索一下有没有什么地方初始化 props
#System.java
private static Properties props;
private static native Properties initProperties(Properties props);
发现了静态方法 initProperties,从方法名上即可知道在类被加载的时候 就初始化了 props, 这是个本地方法,继续跟的话需要看对应的C++代码。
#StandardEnvironment.java
protected void customizePropertySources(MutablePropertySources propertySources) {
//SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME: systemProperties
//跟入
propertySources.addLast(new MapPropertySource(SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME, getSystemProperties()));
propertySources.addLast(new SystemEnvironmentPropertySource(SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, getSystemEnvironment()));
}
#MutablePropertySources.java
/**
* Add the given property source object with lowest precedence.
* 添加属性源,并使其优先级最低
*/
public void addLast(PropertySource<?> propertySource) {
* <p>Where <em>precedence</em> is mentioned in methods such as {@link #addFirst}
* and {@link #addLast}, this is with regard to the order in which property sources
* will be searched when resolving a given property with a {@link PropertyResolver}.
*
* addFist 和 add Last 会设置属性源的优先级,
* PropertyResolver解析配置时会根据优先级使用配置源
*
* @author Chris Beams
* @author Juergen Hoeller
* @since 3.1
* @see PropertySourcesPropertyResolver
*/
public class MutablePropertySources implements PropertySources {

#SpringApplicationRunListeners.java
public void environmentPrepared(ConfigurableEnvironment environment) {
for (SpringApplicationRunListener listener : this.listeners) {
//跟入
listener.environmentPrepared(environment);
}
}
#EventPublishingRunListener.java
public void environmentPrepared(ConfigurableEnvironment environment) {
//广播ApplicationEnvrionmentPreparedEvnet事件
//跟入
this.initialMulticaster.multicastEvent(new ApplicationEnvironmentPreparedEvent(
this.application, this.args, environment));
}
#SimpleApplicationEventMulticaster.java
public void multicastEvent(ApplicationEvent event) {
//跟入
multicastEvent(event, resolveDefaultEventType(event));
} @Override
public void multicastEvent(final ApplicationEvent event, @Nullable ResolvableType eventType) {
ResolvableType type = (eventType != null ? eventType : resolveDefaultEventType(event));
//注意此时 getApplicationListeners(event, type) 返回结果
//包含 监听器 *ConfigFileApplicationListener*
for (final ApplicationListener<?> listener : getApplicationListeners(event, type)) {
Executor executor = getTaskExecutor();
if (executor != null) {
executor.execute(() -> invokeListener(listener, event));
}
else {
//跟入
invokeListener(listener, event);
}
}
}
#SimpleApplicationEventMulticaster.java
/**
* Invoke the given listener with the given event.
* 调用对应事件的监听者
* @param listener the ApplicationListener to invoke
* @param event the current event to propagate
* @since 4.1
*/
protected void invokeListener(ApplicationListener<?> listener, ApplicationEvent event) {
ErrorHandler errorHandler = getErrorHandler();
if (errorHandler != null) {
try {
doInvokeListener(listener, event);
}
catch (Throwable err) {
errorHandler.handleError(err);
}
}
else {
//跟入
doInvokeListener(listener, event);
}
} private void doInvokeListener(ApplicationListener listener, ApplicationEvent event) {
try {
//跟入
listener.onApplicationEvent(event);
}
#ApplicationListener.java
//实现接口的监听器当中,有并跟入ConfigFileApplicationListener的实现
void onApplicationEvent(E event);
#ConfigFileApplicationListener.java
public void onApplicationEvent(ApplicationEvent event) {
if (event instanceof ApplicationEnvironmentPreparedEvent) {
//跟入
onApplicationEnvironmentPreparedEvent(
(ApplicationEnvironmentPreparedEvent) event);
}
if (event instanceof ApplicationPreparedEvent) {
onApplicationPreparedEvent(event);
}
} private void onApplicationEnvironmentPreparedEvent(
ApplicationEnvironmentPreparedEvent event) {
List<EnvironmentPostProcessor> postProcessors = loadPostProcessors();
postProcessors.add(this);
AnnotationAwareOrderComparator.sort(postProcessors);
for (EnvironmentPostProcessor postProcessor : postProcessors) {
//跟入:当postProcessor 为 ConfigFileApplicationListener
postProcessor.postProcessEnvironment(event.getEnvironment(),
event.getSpringApplication());
}
}
#ConfigFileApplicationListener.java
public void postProcessEnvironment(ConfigurableEnvironment environment,
SpringApplication application) {
//跟入
addPropertySources(environment, application.getResourceLoader());
} protected void addPropertySources(ConfigurableEnvironment environment,
ResourceLoader resourceLoader) {
//environment的属性源中包含 systemProperties 属性源 即包含 server.port启动参数
RandomValuePropertySource.addToEnvironment(environment);
//跟入 load()方法
new Loader(environment, resourceLoader).load();
}
跟入load之前,需要了解 java lambda表达式
#ConfigFileApplicationListener.java
public void load() {
this.profiles = new LinkedList<>();
this.processedProfiles = new LinkedList<>();
this.activatedProfiles = false;
this.loaded = new LinkedHashMap<>();
initializeProfiles();
while (!this.profiles.isEmpty()) {
Profile profile = this.profiles.poll();
load(profile, this::getPositiveProfileFilter,
addToLoaded(MutablePropertySources::addLast, false));
this.processedProfiles.add(profile);
}
//跟入
load(null, this::getNegativeProfileFilter,
addToLoaded(MutablePropertySources::addFirst, true));
addLoadedPropertySources();
}
#ConfigFileApplicationListener.java
private void load(Profile profile, DocumentFilterFactory filterFactory,
DocumentConsumer consumer) {
//getSearchLocations()默认返回:
//[./config/, file:./, classpath:/config/, classpath:/]
//即搜索这些路径下的文件
getSearchLocations().forEach((location) -> {
boolean isFolder = location.endsWith("/");
//getSearchNames()返回:application
Set<String> names = (isFolder ? getSearchNames() : NO_SEARCH_NAMES);
//跟入load(.....)
names.forEach(
(name) -> load(location, name, profile, filterFactory, consumer));
});
}
#ConfigFileApplicationListener.java
private void load(String location, String name, Profile profile,
DocumentFilterFactory filterFactory, DocumentConsumer consumer) {
//name默认为:application,所以这个if分支略过
if (!StringUtils.hasText(name)) {
for (PropertySourceLoader loader : this.propertySourceLoaders) {
if (canLoadFileExtension(loader, location)) {
load(loader, location, profile,
filterFactory.getDocumentFilter(profile), consumer);
}
}
}
//this.propertySourceLoaders: PropertiesPropertySourceLoader,YamlPropertySourceLoader
for (PropertySourceLoader loader : this.propertySourceLoaders) {
//PropertiesPropertySourceLoader.getFileExtensions(): properties, xml
//YamlPropertySourceLoader.getFileExtensions(): yml, yaml
for (String fileExtension : loader.getFileExtensions()) {
//location: [./config/, file:./, classpath:/config/, classpath:/]
//name: application
String prefix = location + name;
fileExtension = "." + fileExtension;
//profile: null, dev
//相当于对(location, fileExtension, profile)做笛卡尔积,
//遍历每一种可能,然后加载
//加载文件的细节在loadForFileExtension中完成
loadForFileExtension(loader, prefix, fileExtension, profile,
filterFactory, consumer);
}
}
}
继续跟入 loadForFileExtension 方法,可以了解载入一个配置文件的更多细节。
#ConfigFileApplicationListener.java
public void load() {
this.profiles = new LinkedList<>();
this.processedProfiles = new LinkedList<>();
this.activatedProfiles = false;
this.loaded = new LinkedHashMap<>();
initializeProfiles();
while (!this.profiles.isEmpty()) {
Profile profile = this.profiles.poll();
load(profile, this::getPositiveProfileFilter,
addToLoaded(MutablePropertySources::addLast, false));
this.processedProfiles.add(profile);
}
load(null, this::getNegativeProfileFilter,
addToLoaded(MutablePropertySources::addFirst, true));
//跟入
addLoadedPropertySources();
#ConfigFileApplicationListener.java
private void addLoadedPropertySources() {
//destination: 进入ConfigFileApplicationListener监听器前已有的配置
//即destination中包含 systemProperties 配置源
MutablePropertySources destination = this.environment.getPropertySources();
String lastAdded = null;
//loaded: 此次监听通过扫描文件加载进来的配置源
//loaded: application.yml, appcalition-dev.yml
List<MutablePropertySources> loaded = new ArrayList<>(this.loaded.values());
//倒序后 loaded: application-dev.yml, application.yml
Collections.reverse(loaded);
//先处理 application-dev.yml
for (MutablePropertySources sources : loaded) {
for (PropertySource<?> source : sources) {
//第一次进入: lastAdded:null
if (lastAdded == null) {
if (destination.contains(DEFAULT_PROPERTIES)) {
destination.addBefore(DEFAULT_PROPERTIES, source);
}
else {
//第一次进入: 把application-dev.yml至于最低优先级
destination.addLast(source);
}
}
else {
//第二次进入:
//让 application.yml 优先级比 application-dev.yml 低
destination.addAfter(lastAdded, source);
}
//第一次遍历结束: lastAdded: application-dev
lastAdded = source.getName();
}
}
}
执行后得到各自的优先级,如下图:

从SpringBoot源码分析 配置文件的加载原理和优先级的更多相关文章
- SpringBoot源码分析(二)启动原理
Springboot的jar启动方式,是通过IOC容器启动 带动了Web容器的启动 而Springboot的war启动方式,是通过Web容器(如Tomcat)的启动 带动了IOC容器相关的启动 一.不 ...
- 【MyBatis源码分析】Configuration加载(下篇)
元素设置 继续MyBatis的Configuration加载源码分析: private void parseConfiguration(XNode root) { try { Properties s ...
- 【Spring源码分析】Bean加载流程概览
代码入口 之前写文章都会啰啰嗦嗦一大堆再开始,进入[Spring源码分析]这个板块就直接切入正题了. 很多朋友可能想看Spring源码,但是不知道应当如何入手去看,这个可以理解:Java开发者通常从事 ...
- 【Spring源码分析】Bean加载流程概览(转)
转载自:https://www.cnblogs.com/xrq730/p/6285358.html 代码入口 之前写文章都会啰啰嗦嗦一大堆再开始,进入[Spring源码分析]这个板块就直接切入正题了. ...
- Dubbo源码分析之ExtensionLoader加载过程解析
ExtensionLoader加载机制阅读: Dubbo的类加载机制是模仿jdk的spi加载机制: Jdk的SPI扩展加载机制:约定是当服务的提供者每增加一个接口的实现类时,需要在jar包的META ...
- Android 7.0 Gallery图库源码分析3 - 数据加载及显示流程
前面分析Gallery启动流程时,说了传给DataManager的data的key是AlbumSetPage.KEY_MEDIA_PATH,value值,是”/combo/{/local/all,/p ...
- [ipsec][strongswan] strongswan源码分析--(四)plugin加载优先级原理
前言 如前所述, 我们知道,strongswan以插件功能来提供各种各样的功能.插件之间彼此相互提供功能,同时也有可能提供重复的功能. 这个时候,便需要一个优先级关系,来保证先后加载顺序. 方法 在配 ...
- Spring源码分析:Bean加载流程概览及配置文件读取
很多朋友可能想看Spring源码,但是不知道应当如何入手去看,这个可以理解:Java开发者通常从事的都是Java Web的工作,对于程序员来说,一个Web项目用到Spring,只是配置一下配置文件而已 ...
- 【MyBatis源码分析】Configuration加载(上篇)
config.xml解析为org.w3c.dom.Document 本文首先来简单看一下MyBatis中将config.xml解析为org.w3c.dom.Document的流程,代码为上文的这部分: ...
随机推荐
- C/C++编程语言制作《游戏内存外挂》
通过C/C++编程语言编写一个简单的外挂,通过 API 函数修改游戏数据,从而实现作弊功能 对象分析要用的 API 函数简单介绍编写测试效果. 下面是我整理好的全套C/C++资料,加入天狼QQ7269 ...
- Spring的学习与实战
目录 一.Spring起步 学习路线图 Spring的基础知识 什么是Spring Spring框架核心模块 SpringBoot 第一个Spring应用DEMO 编写自己的第一个SpringMVC例 ...
- mysql 漏洞利用与提权
判断MySQL服务运行的权限 1.查看系统账号,如果出现MySQL这类用户,意味着系统可能出现了降权. 2.看mysqld运行的priority值. 3.查看端口是否可外联. MySQL密码获取与破解 ...
- MCU 51-4 独立按键&编码按键
独立按键: 按键的按下与释放是通过机械触点的闭合与断开来实现的,因机械触点的弹性作用,在闭合与断开的瞬间均有一个抖动的过程,抖动必须清除. 按键按下一次,数码管数值加1: #include<re ...
- scala 数据结构(二):数组
1 数组-定长数组(声明泛型) 第一种方式定义数组 这里的数组等同于Java中的数组,中括号的类型就是数组的类型 val arr1 = new Array[Int](10) //赋值,集合元素采用小括 ...
- web 部署专题(三):压力测试(一)工具 siege
1.介绍 Siege是一个压力测试和评测工具,设计用于WEB开发这评估应用在压力下的承受能力:可以根据配置对一个WEB站点进行多用户的并发访问,记录每个用户所有请求过程的相应时间,并在一定数量的并发访 ...
- 数据分析06 /pandas高级操作相关案例:人口案例分析、2012美国大选献金项目数据分析
数据分析06 /pandas高级操作相关案例:人口案例分析.2012美国大选献金项目数据分析 目录 数据分析06 /pandas高级操作相关案例:人口案例分析.2012美国大选献金项目数据分析 1. ...
- 数据分析05 /pandas的高级操作
数据分析05 /pandas的高级操作 目录 数据分析05 /pandas的高级操作 1. 替换操作 2. 映射操作 3. 运算工具 4. 映射索引 / 更改之前索引 5. 排序实现的随机抽样/打乱表 ...
- CSS 三大特性 层叠 继承 优先级
css三大特性 层叠性: 如果一个属性通过两个相同选择器设置到同一个元素上,相同的属性就会出现冲突,那么这个时候一个属性就会将另一个属性层叠掉,采用的是就近原则 继承性: 子标签会继承父标签的某些样式 ...
- Java对象与Json字符串的转换
Java对象与Json字符串的转换 JSON是一种轻量级的数据交换格式,常用于前后端的数据交流 后端 : 前端 Java对象 > JsonString Java对象 < jsonStrin ...