SpringBoot配置檔案讀取過程分析

bei_er發表於2022-07-17

整體流程分析

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]));
}

相關文章