SpringBoot中唯一的配置文件就是application.properties了,那这个配置文件是在什么时候被加载的,存储在什么地方,又是如何被使用的呢?下面从源码的角度来分析
1、application.properties的加载
springboot加载的配置文件是放在environment中的,在prepareEnvironment的时候,springboot读取和加载了application.properties文件
environment的详细解析见https://blog.csdn.net/woshilijiuyi/article/details/82720478
跟进prepareEnvironment方法
private ConfigurableEnvironment prepareEnvironment(
SpringApplicationRunListeners listeners,
ApplicationArguments applicationArguments) {
//1、初始化environment
ConfigurableEnvironment environment = getOrCreateEnvironment();
//2、加载默认配置
configureEnvironment(environment, applicationArguments.getSourceArgs());
//3、通知环境监听器,加载项目中的配置文件
listeners.environmentPrepared(environment);
if (!this.webEnvironment) {
environment = new EnvironmentConverter(getClassLoader())
.convertToStandardEnvironmentIfNecessary(environment);
}
return environment;
}
这里主要分析listeners.environmentPrepared(environment)方法中,监听器是如何加载配置文件的
public void environmentPrepared(ConfigurableEnvironment environment) {
//new了一个environmentPrepared的事件
this.initialMulticaster.multicastEvent(new ApplicationEnvironmentPreparedEvent(
this.application, this.args, environment));
}
//这里就很眼熟了,这就是上一章监听器的工作原理
public void multicastEvent(final ApplicationEvent event, ResolvableType eventType) {
ResolvableType type = (eventType != null ? eventType : resolveDefaultEventType(event));
for (final ApplicationListener<?> listener : getApplicationListeners(event, type)) {
Executor executor = getTaskExecutor();
if (executor != null) {
executor.execute(new Runnable() {