SpringBoot配置文件讀取過程分析

整體流程分析

SpringBoot的配置文件有兩種 ,一種是 properties文件,一種是yml文件。在SpringBoot啟動過程中會對這些文件進行解析載入。在SpringBoot啟動的過程中,配置文件查找和解析的邏輯在listeners.environmentPrepared(environment)方法中。

void environmentPrepared(ConfigurableEnvironment environment) {
    for (SpringApplicationRunListener listener : this.listeners) {
        listener.environmentPrepared(environment);
    }
}

依次遍歷監聽器管理器的environmentPrepared方法,默認只有一個 EventPublishingRunListener 監聽器管理器,程式碼如下,

@Override
public void environmentPrepared(ConfigurableEnvironment environment) {
    this.initialMulticaster
        .multicastEvent(new ApplicationEnvironmentPreparedEvent(this.application, this.args, environment));
}

監聽管理器的多播器有中有11個,其中針對配置文件的監聽器類為 ConfigFileApplicationListener,會執行該類的 onApplicationEvent方法。程式碼如下,

@Override
public void onApplicationEvent(ApplicationEvent event) {
    if (event instanceof ApplicationEnvironmentPreparedEvent) {
        // 執行 ApplicationEnvironmentPreparedEvent 事件
        onApplicationEnvironmentPreparedEvent((ApplicationEnvironmentPreparedEvent) event);
    }
    if (event instanceof ApplicationPreparedEvent) {
        onApplicationPreparedEvent(event);
    }
}

onApplicationEnvironmentPreparedEvent的邏輯為:先從/META-INF/spring.factories文件中獲取實現了EnvironmentPostProcessor介面的環境變數後置處理器集合,再把當前的 ConfigFileApplicationListener 監聽器添加到 環境變數後置處理器集合中(ConfigFileApplicationListener實現了EnvironmentPostProcessor介面),然後循環遍歷 postProcessEnvironment 方法,並傳入 事件的SpringApplication 對象和 環境變數。

private void onApplicationEnvironmentPreparedEvent(ApplicationEnvironmentPreparedEvent event) {
    List<EnvironmentPostProcessor> postProcessors = loadPostProcessors();
    postProcessors.add(this);
    AnnotationAwareOrderComparator.sort(postProcessors);
    for (EnvironmentPostProcessor postProcessor : postProcessors) {
        postProcessor.postProcessEnvironment(event.getEnvironment(), event.getSpringApplication());
    }
}

在ConfigFileApplicationListener 的postProcessEnvironment方法中(其他幾個環境變數後置處理器與讀取配置文件無關),核心是創建了一個Load對象,並且調用了load()方法。

protected void addPropertySources(ConfigurableEnvironment environment, ResourceLoader resourceLoader) {
    RandomValuePropertySource.addToEnvironment(environment);
    new Loader(environment, resourceLoader).load();
}
  1. Loader是ConfigFileApplicationListener 的一個內部類,在Loader的構造方法中,會生成具體屬性文件的資源載入類並賦值給this.propertySourceLoaders。程式碼如下,
Loader(ConfigurableEnvironment environment, ResourceLoader resourceLoader) {
    this.environment = environment;
    this.placeholdersResolver = new PropertySourcesPlaceholdersResolver(this.environment);
    this.resourceLoader = (resourceLoader != null) ? resourceLoader : new DefaultResourceLoader();
    //從 /META-INF/spring.factories 中載入 PropertySourceLoader 的實現類
    this.propertySourceLoaders = SpringFactoriesLoader.loadFactories(PropertySourceLoader.class,
                                                                     getClass().getClassLoader());
}

從 /META-INF/spring.factories 中載入 PropertySourceLoader 的實現類,在具體解析資源文件的時候用到。具體的實現類如下,

org.springframework.boot.env.PropertySourceLoader=\
org.springframework.boot.env.PropertiesPropertySourceLoader,\
org.springframework.boot.env.YamlPropertySourceLoader
  1. Loader類的load方法是載入配置文件的入口方法,程式碼如下,
void load() {
    FilteredPropertySource.apply(...)
}

FilteredPropertySource.apply()方法先判斷是否存在以 defaultProperties 為名的 PropertySource 屬性對象,如果不存在則執行operation.accept,如果存在則先替換,再執行operation.accept方法。程式碼如下:

static void apply(ConfigurableEnvironment environment, String propertySourceName, Set<String> filteredProperties,
                  Consumer<PropertySource<?>> operation) {
    // 在環境變數中獲取 屬性資源管理對象
    MutablePropertySources propertySources = environment.getPropertySources();
    // 根據 資源名稱 獲取屬性資源對象
    PropertySource<?> original = propertySources.get(propertySourceName);
    // 如果為null,則執行 operation.accept
    if (original == null) {
        operation.accept(null);
        return;
    }
    //根據propertySourceName名稱進行替換
    propertySources.replace(propertySourceName, new FilteredPropertySource(original, filteredProperties));
    try {
        operation.accept(original);
    }
    finally {
        propertySources.replace(propertySourceName, original);
    }
}
  1. operation.accept是一個函數介面,配置文件的解析和處理都在該方法中。具體的邏輯為:先初始化待處理的屬性文件,再遍歷解析待處理的屬性文件並解析結果放在this.loaded中,然後添加this.loaded的數據至環境變數 this.environment.getPropertySources() 中,最後設置環境變數的ActiveProfiles屬性。程式碼如下,
// 待處理的屬性文件
this.profiles = new LinkedList<>();
// 已處理的屬性文件
this.processedProfiles = new LinkedList<>();
this.activatedProfiles = false;
// 已經載入的 屬性文件和屬性
this.loaded = new LinkedHashMap<>();
// 添加 this.profiles 的 null 和 默認的屬性文件
initializeProfiles();
// 循環 this.profiles 載入
while (!this.profiles.isEmpty()) {
    Profile profile = this.profiles.poll();
    // 如果是主屬性文件則先添加到環境變數中的 addActiveProfile
    if (isDefaultProfile(profile)) {
        addProfileToEnvironment(profile.getName());
    }
    // 真正載入邏輯
    load(profile, this::getPositiveProfileFilter,
         addToLoaded(MutablePropertySources::addLast, false));
    this.processedProfiles.add(profile);
}
// 載入 profile 為null 的
load(null, this::getNegativeProfileFilter, addToLoaded(MutablePropertySources::addFirst, true));
// 添加已經載入的 屬性文件和屬性至 環境變數 this.environment.getPropertySources() 中 
addLoadedPropertySources();
//根據已處理的屬性文件設置環境變數的ActiveProfiles
applyActiveProfiles(defaultProperties);

配置文件解析過程

  1. 如上的load()的邏輯為:先獲取所有的查找路徑,再遍歷查找路徑並且獲取屬性配置文件的名稱,最後根據名稱和路徑進行載入。這裡會在 file:./config/,file:./,classpath:/config/,classpath:/ 四個不同的目錄進行查找。優先順序從左至右。
private void load(Profile profile, DocumentFilterFactory filterFactory, DocumentConsumer consumer) {
    // 獲取 默認的 classpath:/,classpath:/config/,file:./,file:./config/ 文件路徑
    // 根據路徑查找具體的屬性配置文件
    getSearchLocations().forEach((location) -> {
        // 判斷是否為文件夾
        boolean isFolder = location.endsWith("/");
        // 獲取 屬性配置文件的名稱
        Set<String> names = isFolder ? getSearchNames() : NO_SEARCH_NAMES;
        // 根據名稱遍歷進行載入具體路徑下的具體的屬性文件名
        names.forEach((name) -> load(location, name, profile, filterFactory, consumer));
    });
}
  1. getSearchLocations()獲取屬性文件搜索路徑,如果環境變數中包括了 spring.config.location 則使用環境變數中配置的值,如果沒有則使用默認的 file:./config/,file:./,classpath:/config/,classpath:/文件路徑。程式碼如下,
// 獲取搜索路徑
private Set<String> getSearchLocations() {
    // 如果環境變數中包括了 spring.config.location 則使用 環境變數配置的值。
    if (this.environment.containsProperty(CONFIG_LOCATION_PROPERTY)) {
        return getSearchLocations(CONFIG_LOCATION_PROPERTY);
    }
    // 獲取 環境變數 spring.config.additional-location 的值
    Set<String> locations = getSearchLocations(CONFIG_ADDITIONAL_LOCATION_PROPERTY);
    // 添加默認的 classpath:/,classpath:/config/,file:./,file:./config/ 搜索文件
    // 倒敘排列後 為 file:./config/,file:./,classpath:/config/,classpath:/
    locations.addAll(
        asResolvedSet(ConfigFileApplicationListener.this.searchLocations, DEFAULT_SEARCH_LOCATIONS));
    return locations;
}
  1. getSearchNames()獲取屬性文件搜索名稱,如果環境變數中有設置 spring.config.name 屬性,則獲取設置的名稱,如果沒有設置配置文件名稱的環境變數則返回名稱為 application。程式碼如下,
private Set<String> getSearchNames() {
    // 如果 環境變數中有設置 spring.config.name 屬性,則獲取設置的 名稱
    if (this.environment.containsProperty(CONFIG_NAME_PROPERTY)) {
        String property = this.environment.getProperty(CONFIG_NAME_PROPERTY);
        return asResolvedSet(property, null);
    }
    // 如果沒有設置環境變數 則返回名稱為 application
    return asResolvedSet(ConfigFileApplicationListener.this.names, DEFAULT_NAMES);
}
  1. names.forEach((name) -> load(location, name, profile, filterFactory, consumer))中的load() 的邏輯為:先判斷文件名name是否為null,如果為null則通過遍歷屬性資源載入器並且根據location進行載入屬性資源文件;如果不為null ,則通過遍歷屬性資源載入器和遍歷屬性資源載入器的擴展名,根據location和 name 來載入屬性資源文件,從配置文件可知,先會遍歷執行 PropertiesPropertySourceLoader 的擴展名 ,然後遍歷執行YamlPropertySourceLoader的擴展名 。程式碼如下,
private void load(String location, String name, Profile profile, DocumentFilterFactory filterFactory,
                  DocumentConsumer consumer) {
    // 如果文件名稱為null
    if (!StringUtils.hasText(name)) {
        // 遍歷屬性資源載入器
        for (PropertySourceLoader loader : this.propertySourceLoaders) {
            // 根據屬性資源載入的擴展名稱進行過濾
            if (canLoadFileExtension(loader, location)) {
                load(loader, location, profile, filterFactory.getDocumentFilter(profile), consumer);
                return;
            }
        }
        throw new IllegalStateException("File extension of config file location '" + location
                                        + "' is not known to any PropertySourceLoader. If the location is meant to reference "
                                        + "a directory, it must end in '/'");
    }
    Set<String> processed = new HashSet<>();
    // 遍歷屬性資源載入器
    for (PropertySourceLoader loader : this.propertySourceLoaders) {
        // 遍歷屬性資源載入器的擴展名
        for (String fileExtension : loader.getFileExtensions()) {
            if (processed.add(fileExtension)) {
                // 傳入具體的屬性文件路徑和後綴名,進行載入屬性資源文件
                loadForFileExtension(loader, location + name, "." + fileExtension, profile, filterFactory,
                                     consumer);
            }
        }
    }
}
  1. loadForFileExtension()關鍵程式碼是load()方法,程式碼如下。
private void loadForFileExtension(PropertySourceLoader loader, String prefix, String fileExtension,
                                  Profile profile, DocumentFilterFactory filterFactory, DocumentConsumer consumer) {
    DocumentFilter defaultFilter = filterFactory.getDocumentFilter(null);
    DocumentFilter profileFilter = filterFactory.getDocumentFilter(profile);
    if (profile != null) {
        // Try profile-specific file & profile section in profile file (gh-340)
        String profileSpecificFile = prefix + "-" + profile + fileExtension;
        load(loader, profileSpecificFile, profile, defaultFilter, consumer);
        load(loader, profileSpecificFile, profile, profileFilter, consumer);
        // Try profile specific sections in files we've already processed
        for (Profile processedProfile : this.processedProfiles) {
            if (processedProfile != null) {
                String previouslyLoaded = prefix + "-" + processedProfile + fileExtension;
                load(loader, previouslyLoaded, profile, profileFilter, consumer);
            }
        }
    }
    // Also try the profile-specific section (if any) of the normal file
    // 拼接文件路徑和後綴名後,進行載入屬性資源文件
    load(loader, prefix + fileExtension, profile, profileFilter, consumer);
}
  1. 如上程式碼的load()方法主要邏輯為:先根據傳入的文件路徑生成 Resource 對象,如果該Resource 對象存在則解析成具體的documents對象,然後根據DocumentFilter 過濾器進行匹配,匹配成功則添加到 loaded 中,再進行倒敘排列。最後遍歷 loaded 對象,調用consumer.accept ,將 profile 和 document 添加至 this.loaded 對象。
private void load(PropertySourceLoader loader, String location, Profile profile, DocumentFilter filter,
                  DocumentConsumer consumer) {
    try {
        // 根據文件路徑 獲取資源
        Resource resource = this.resourceLoader.getResource(location);
        // 如果為 null 則返回
        if (resource == null || !resource.exists()) {
            if (this.logger.isTraceEnabled()) {
                StringBuilder description = getDescription("Skipped missing config ", location, resource,
                                                           profile);
                this.logger.trace(description);
            }
            return;
        }
        if (!StringUtils.hasText(StringUtils.getFilenameExtension(resource.getFilename()))) {
            if (this.logger.isTraceEnabled()) {
                StringBuilder description = getDescription("Skipped empty config extension ", location,
                                                           resource, profile);
                this.logger.trace(description);
            }
            return;
        }
        String name = "applicationConfig: [" + location + "]";
        // 根據資源 和 屬性資源解析器載入 List<Document> ,並進行快取
        List<Document> documents = loadDocuments(loader, name, resource);
        if (CollectionUtils.isEmpty(documents)) {
            if (this.logger.isTraceEnabled()) {
                StringBuilder description = getDescription("Skipped unloaded config ", location, resource,
                                                           profile);
                this.logger.trace(description);
            }
            return;
        }
        List<Document> loaded = new ArrayList<>();
        // 遍歷 documents
        for (Document document : documents) {
            // 如果匹配則添加
            if (filter.match(document)) {
                addActiveProfiles(document.getActiveProfiles());
                addIncludedProfiles(document.getIncludeProfiles());
                loaded.add(document);
            }
        }
        // 倒敘排列
        Collections.reverse(loaded);
        if (!loaded.isEmpty()) {
           	//遍歷 loaded 對象,調用consumer.accept ,將 profile 和 document 添加至 this.loaded 對象
            loaded.forEach((document) -> consumer.accept(profile, document));
            if (this.logger.isDebugEnabled()) {
                StringBuilder description = getDescription("Loaded config file ", location, resource, profile);
                this.logger.debug(description);
            }
        }
    }
    catch (Exception ex) {
        throw new IllegalStateException("Failed to load property source from location '" + location + "'", ex);
    }
}
  1. 至此配置文件解析全部處理完成,最終會把解析出來的配置文件和配置屬性值添加到了 this.loaded 對象中。
  2. 總結一下,默認情況下,屬性配置文件的搜索路徑為 file:./config/,file:./,classpath:/config/,classpath:/ ,優先順序從左往右;配置文件名稱為 application,擴展名為”properties”, “xml”,”yml”, “yaml”,優先順序從左往右。如果同一個配置屬性配置在多個配置文件中,則取優先順序最高的那個配置值。

環境變數設置配置屬性

  1. addLoadedPropertySources()方法,主要邏輯為:添加已經載入的屬性文件添加至環境變數 this.environment 中 。程式碼如下,
private void addLoadedPropertySources() {
    // 獲取環境變數的 PropertySources對象
    MutablePropertySources destination = this.environment.getPropertySources();
    List<MutablePropertySources> loaded = new ArrayList<>(this.loaded.values());
    // 倒序排列
    Collections.reverse(loaded);
    String lastAdded = null;
    Set<String> added = new HashSet<>();
    for (MutablePropertySources sources : loaded) {
        for (PropertySource<?> source : sources) {
            if (added.add(source.getName())) {
                // 添加 PropertySource 至 destination
                addLoadedPropertySource(destination, lastAdded, source);
                lastAdded = source.getName();
            }
        }
    }
}
  1. applyActiveProfiles()主要邏輯為:根據已處理的屬性文件設置環境變數environment的ActiveProfiles屬性。
// 設置環境變數的ActiveProfiles
private void applyActiveProfiles(PropertySource<?> defaultProperties) {
    List<String> activeProfiles = new ArrayList<>();
    if (defaultProperties != null) {
        Binder binder = new Binder(ConfigurationPropertySources.from(defaultProperties),
                                   new PropertySourcesPlaceholdersResolver(this.environment));
        activeProfiles.addAll(getDefaultProfiles(binder, "spring.profiles.include"));
        if (!this.activatedProfiles) {
            activeProfiles.addAll(getDefaultProfiles(binder, "spring.profiles.active"));
        }
    }
    this.processedProfiles.stream().filter(this::isDefaultProfile).map(Profile::getName)
        .forEach(activeProfiles::add);
    this.environment.setActiveProfiles(activeProfiles.toArray(new String[0]));
}