SpringBoot外部化配置使用Plus版

本文如有任何紕漏、錯誤,請不吝指正!

PS: 之前寫過一篇關於SpringBoo中使用配置文件的一些姿勢,不過嘛,有句話(我)說的好:曾見小橋流水,未睹觀音坐蓮!所以再寫一篇增強版,以便記錄。

序言

上一篇博客記錄,主要集中在具體的配置內容,也就是使用@ConfigurationProperties這個註解來進行配置與結構化對象的綁定,雖然也順帶說了下@Value的使用以及其區別。

在這篇記錄中,打算從總覽,鳥瞰的俯視視角,來從整體上對SpringBoot,乃至Spring Framework對於外部化配置文件處理,以及配置參數的綁定操作,是如果處理的、怎麼設計的。

這裏其實主要說的是 SpringBoot,雖然@Value屬於Spring Framework的註解,不過在SpringBoot中也被頻繁使用。

SpringBoot版本: 2.2.6.RELEASE

SpringBoot啓動流程簡介

SpringBoot的啓動過程中,大體上分爲三步

第一步:prepareEnvironment,準備SpringBoot執行時所有的配置。

第二步:prepareContext,根據啓動時的傳入的配置類,創建其BeanDefinition

第三步:refreshContext,真正啓動上下文。

在這上面三步中,第一步結束後,我們所需要的或者配置文件配置的內容,大部分已經被加載進來,然後在第三步中進行配置的注入或者綁定操作。

至於爲什麼是大部分,後面會有解釋。

將配置從配置文件加載到Environment中,使用的是事件通知的方式。

本篇博客記錄僅僅聚焦第一步中如何讀取配置文件的分析,順帶介紹下第三步的注入和綁定。

受限於技術水平,僅能達到這個程度

外部化配置方式

如果有看到SpringBoot官網關於外部化配置的說明,就會驚訝的發現,原來SpringBoot有那麼多的配置來源。

SpringBoot關於外部化配置特性的文檔說明,直達地址

而實際使用中,通常可能會使用的比較多的是通過以下這些 方式

commandLine

通過在啓動jar時,加上-DconfigKey=configValue或者 --configKey=configValue的方式,來進行配置,多個配置項用空格分隔。

這種使用場景也多,只是一般用於一些配置內容很少且比較關鍵的配置,比如說可以決定運行環境的配置。

不易進行比較多的或者配置內容比較冗長的配置,容易出錯,且不便於維護管理。

application

這種是SpringBoot提供的,用於簡便配置的一種方式,只要我們將應用程序所用到的配置,直接寫到application.properties中,並將文件放置於以下四個位置即可 。

  1. 位於jar同目錄的config目錄下的application.properties
  2. 位於jar同目錄的application.properties
  3. classpath下的configapplication.properties
  4. classpath下的application.properties

以上配置文件類型也都可以使用yml

默認情況下,這種方式是SpringBoot約定好的一種方式,文件名必須爲application,文件內容格式可以爲Yaml或者Properties,也許支持XML,因爲看源碼是支持的,沒有實踐。

好處就是簡單,省心省事,我們只需關注文件本身的內容就可,其他的無需關心,這也是 SpringBoot要追求的結果。

缺點也很明顯,如果配置內容比較冗長,爲了便於管理維護,增加可讀性,必須要對配置文件進行切分,通過功能等維度進行分類分組,使用多個配置文件來進行存放配置數據。

SpringBoot也想到了這些問題,因此提供了下面兩個比較方便的使用方式,來應對這種情況

profiles

profiles本身是也是一個配置項,它提供一種方式將部分應用程序配置進行隔離,並且使得它僅在具體某一個環境中可用。

具體實踐中常用的主要是針對不同的環境,有開發環境用到的特有配置值,有測試環境特有的配置,有生產環境特有的配置,包括有些Bean根據環境選擇決定是否進行實例化,這些都是通過profiles來實現的。不過這裏只關注配置這一塊內容。

它的使用方式通常是spring.profiles.active=dev,dev1或者 spring.profiles.include=db1,db2

這裏可以看到有兩種不同的用法,這兩種方式是有區別的。

如果在application.properties中定義了一個spring.profiles.active=dev,而後在啓動時通過 命令行又寫了個 --spring.profiles.active=test,那麼最終使用的是test,而不是dev

如果同樣的場景下,使用spring.profiles.include來替換spring.profiles.active,那麼結果會是devtest都會存在,而不是替換的行爲 。

這就是兩個之間的差別,這種差別也使得他們使用的場景並不一樣,active更適合那些需要互斥的環境,而include則是多個並存的配置。

僅僅配置了profiles是沒有意義的,必須要有相應的配置文件配合一起使用,而且這些配置文件的命名要符合一定的規則,否則配置文件不會被加載進Environment的。

profiles文件的命名規則爲application-*.properties,同樣的,application.properties能放置的位置它也可以,不能的,它也不可以。

propery source

註解@PropertySource可以寫在配置類上,並且指定要讀取的配置文件路徑,這個路徑可以是絕對路徑,也可以是相對路徑。

它可以有以下幾種配置

  1. @PropertySource("/config.properties")
  2. @PropertySource("config.properties")
  3. @PropertySource("file:/usr/local/config.properties")
  4. @PropertySource("file:./config.properties")
  5. @PropertySource("${pathPrefix}/config.properties")

其中1和2兩種方式是一樣的,都是從classpath去開始查找的

3和4是使用文件系統的絕對和相對路徑的方式,這裏絕對路徑比較好理解 ,相對路徑則是從項目的根目錄作爲相對目錄的,如果是jar包的方式運行,就是jar所在的目錄。

5是結合SpEL的表達式來使用的,可以直接從環境中獲取配置好的路徑。
注意@PropertySource指定的文件一定是要存在的,默認情況下文件類型爲Properties,可以通過自定義PropertySourceFactory來讀取其他的格式

FBI Warning : 第一種和第二種配置時,直接跑不會有問題,但是跑單元測試時出了問題,建議加上classpath:,原因在這裏解釋

以上幾種方式在實際開發中遇到和SpringBoot相關的配置,基本都能應付過來了。

不過對於上面配置的一些原理性的內容,還沒有提到 ,下面會簡單說一下SpringBoot關於配置更詳細的處理,以及配置的優先級的問題。

原理淺入淺出

帶着問題去找原因,比較有目的性和針對性,效果也相對好一些。

所以這裏描述幾個會引起疑問的現象

默認情況下自動加載的配置文件命名必須要是application

在使用application.properties時,可以同時在四個位置放置配置,配置的優先級就是上面羅列時顯示的優先級。同樣的配置,優先級高的生效,優先級低的忽略。

profiles引入的配置,也準守同樣的優先級規則

命令行配置具有最高優先級

有些配置不能使用@PropertySource的方式進行注入,比如日誌的配置。

如果一個配置類使用了@ConfigurationProperties,然後字段使用了@Value@ConfigurationProperties先被處理,@Value後被處理。

源碼簡讀

SpringBoot讀取application.properties配置

查看org.springframework.boot.context.config.ConfigFileApplicationListener的源碼

public class ConfigFileApplicationListener implements EnvironmentPostProcessor, SmartApplicationListener, Ordered {
    // Note the order is from least to most specific (last one wins)
    // 默認檢索配置文件的路徑,優先級越來越高,
    // 可以通過 spring.config.location重新指定,要早於當前類執行時配置好
	private static final String DEFAULT_SEARCH_LOCATIONS = "classpath:/,classpath:/config/,file:./,file:./config/";
    // 默認的配置名,可以通過命令行配置--spring.config.name=xxx來重新指定
    // 不通過命令行也可以通過其他方式,環境變量這些。
	private static final String DEFAULT_NAMES = "application";
  
    private class Loader {
        // 找到配置的路徑
        private Set<String> getSearchLocations() {
            if (this.environment.containsProperty(CONFIG_LOCATION_PROPERTY)) {
            return getSearchLocations(CONFIG_LOCATION_PROPERTY);
            }
            Set<String> locations = getSearchLocations(CONFIG_ADDITIONAL_LOCATION_PROPERTY);
            locations.addAll(
                asResolvedSet(ConfigFileApplicationListener.this.searchLocations, DEFAULT_SEARCH_LOCATIONS));
            return locations;
  	    }
        // 解析成Set
		private Set<String> asResolvedSet(String value, String fallback) {
			List<String> list = Arrays.asList(StringUtils.trimArrayElements(StringUtils.commaDelimitedListToStringArray(
					(value != null) ? this.environment.resolvePlaceholders(value) : fallback)));
			// 這裏會做一個反轉,也就是配置的路徑中,放在後面的優先級越高
            Collections.reverse(list);
			return new LinkedHashSet<>(list);
		}
    	private Set<String> getSearchNames() {
			if (this.environment.containsProperty(CONFIG_NAME_PROPERTY)) {
				String property = this.environment.getProperty(CONFIG_NAME_PROPERTY);
				return asResolvedSet(property, null);
			}
			return asResolvedSet(ConfigFileApplicationListener.this.names, DEFAULT_NAMES);
		}
  }
  
}

命令行的配置具有最高優先級

protected void configurePropertySources(ConfigurableEnvironment environment, String[] args) {
    MutablePropertySources sources = environment.getPropertySources();
    if (this.defaultProperties != null && !this.defaultProperties.isEmpty()) {
        sources.addLast(new MapPropertySource("defaultProperties", this.defaultProperties));
    }
    // 支持從命令行添加屬性以及存在參數時
    if (this.addCommandLineProperties && args.length > 0) {
        String name = CommandLinePropertySource.COMMAND_LINE_PROPERTY_SOURCE_NAME;
        // 這裏是看下是不是存在同名的配置了
        if (sources.contains(name)) {
            PropertySource<?> source = sources.get(name);
            CompositePropertySource composite = new CompositePropertySource(name);
            composite.addPropertySource(
                new SimpleCommandLinePropertySource("springApplicationCommandLineArgs", args));
            composite.addPropertySource(source);
            sources.replace(name, composite);
        }
        else {
            // 直接添加,並且是添加到第一個位置,具有最高優先級
            sources.addFirst(new SimpleCommandLinePropertySource(args));
        }
   }
}

@PropertySource是在refreshContext階段,執行BeanDefinitionRegistryPostProcessor時處理的

// org.springframework.context.annotation.ConfigurationClassParser#processPropertySource
private void processPropertySource(AnnotationAttributes propertySource) throws IOException {
    String name = propertySource.getString("name");
    if (!StringUtils.hasLength(name)) {
        name = null;
    }
    String encoding = propertySource.getString("encoding");
    if (!StringUtils.hasLength(encoding)) {
        encoding = null;
    }
    // 獲取配置的文件路徑
    String[] locations = propertySource.getStringArray("value");
    Assert.isTrue(locations.length > 0, "At least one @PropertySource(value) location is required");
    boolean ignoreResourceNotFound = propertySource.getBoolean("ignoreResourceNotFound");
    // 指定的讀取配置文件的工廠
    Class<? extends PropertySourceFactory> factoryClass = propertySource.getClass("factory");
    // 沒有就用默認的 
    PropertySourceFactory factory = (factoryClass == PropertySourceFactory.class ?
         DEFAULT_PROPERTY_SOURCE_FACTORY : BeanUtils.instantiateClass(factoryClass));
    // 循環加載
    for (String location : locations) {
        try {
            // 會解析存在佔位符的情況
            String resolvedLocation = this.environment.resolveRequiredPlaceholders(location);
            // 使用DefaultResourceLoader來加載資源
            Resource resource = this.resourceLoader.getResource(resolvedLocation);
            // 創建PropertySource對象
            addPropertySource(factory.createPropertySource(name, new EncodedResource(resource, encoding)));
        }
        catch (IllegalArgumentException | FileNotFoundException | UnknownHostException ex) {
            // Placeholders not resolvable or resource not found when trying to open it
            if (ignoreResourceNotFound) {
                if (logger.isInfoEnabled()) {
                    logger.info("Properties location [" + location + "] not resolvable: " + ex.getMessage());
                }
            }
            else {
                throw ex;
            }
        }
   }
}

因爲執行時機的問題,有些配置不能使用@PropertySource,因爲這個時候對有些配置來說,如果使用這種配置方式,黃花菜都涼了。同時這個註解要配合@Configuration註解一起使用才能生效,使用@Component是不行的。

處理@ConfigurationProperty的處理器是一個BeanPostProcessor,處理@Value的也是一個BeanPostProcessor,不過他倆的優先級並不一樣,

// @ConfigurationProperty
public class ConfigurationPropertiesBindingPostProcessor
      implements BeanPostProcessor, PriorityOrdered, ApplicationContextAware, InitializingBean {
    @Override
	public int getOrder() {
		return Ordered.HIGHEST_PRECEDENCE + 1;
	}

}
// @Value
public class AutowiredAnnotationBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter
		implements MergedBeanDefinitionPostProcessor, PriorityOrdered, BeanFactoryAware {
	private int order = Ordered.LOWEST_PRECEDENCE - 2;
    @Override
	public int getOrder() {
		return this.order;
    }
}

從上面可以看出處理@ConfigurationPropertyBeanPostProcessor優先級很高,而@ValueBeanPostProcessor優先級很低。

使用@Value注入時,要求配置的key必須存在於Environment中的,否則會終止啓動,而@ConfigurationProperties則不會。

@Value可以支持SpEL表達式,也支持佔位符的方式。

自定義配置讀取

org.springframework.boot.context.config.ConfigFileApplicationListener是一個監聽器,同時也是一個EnvironmentPostProcessor,在有ApplicationEnvironmentPreparedEvent事件觸發時,會去處理所有的EnvironmentPostProcessor的實現類,同時這些個實現也是使用SpringFactoriesLoader的方式來加載的。

對於配置文件的讀取,就是使用的這種方式。

@Override
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.postProcessEnvironment(event.getEnvironment(), event.getSpringApplication());
    }
}

有了這個擴展點後,我們就能自己定義讀取任何配置,從任何地方。

只要實現了EnvironmentPostProcessor接口,並且在META-INF/spring.factories中配置一下

org.springframework.boot.env.EnvironmentPostProcessor=com.example.configuration.ConfigurationFileLoader

附一個自己寫的例子

public class ConfigurationFileLoader implements EnvironmentPostProcessor {

    private static final String DEFAULT_SEARCH_LOCATIONS = "classpath:/,classpath:/config/,file:./,file:./config/";
    private static final String DEFAULT_NAMES = "download";
    private static final String DEFAULT_FILE_EXTENSION = ".yml";


    @Override
    public void postProcessEnvironment (ConfigurableEnvironment environment,
                                        SpringApplication application) {

        List<String> list = Arrays.asList(StringUtils.trimArrayElements(
                StringUtils.commaDelimitedListToStringArray(DEFAULT_SEARCH_LOCATIONS)));
        Collections.reverse(list);
        Set<String> reversedLocationSet = new LinkedHashSet(list);
        ResourceLoader defaultResourceLoader = new DefaultResourceLoader();
        YamlPropertiesFactoryBean yamlPropertiesFactoryBean = new YamlPropertiesFactoryBean();
        List<Properties> loadedProperties = new ArrayList<>(2);
        reversedLocationSet.forEach(location->{
            Resource resource = defaultResourceLoader.getResource(location + DEFAULT_NAMES+DEFAULT_FILE_EXTENSION);
            if (resource == null || !resource.exists()) {
                return;
            }
            yamlPropertiesFactoryBean.setResources(resource);
            Properties properties = yamlPropertiesFactoryBean.getObject();
            loadedProperties.add(properties);
        });

        Properties filteredProperties = new Properties();
        Set<Object> addedKeys = new LinkedHashSet<>();
        for (Properties propertySource : loadedProperties) {
            for (Object key : propertySource.keySet()) {
                String stringKey = (String) key;
                if (addedKeys.add(key)) {
                    filteredProperties.setProperty(stringKey, propertySource.getProperty(stringKey));
                }

            }
        }
        PropertiesPropertySource propertySources = new PropertiesPropertySource(DEFAULT_NAMES, filteredProperties);
        environment.getPropertySources().addLast(propertySources);
    }
}

基本上都是 參考ConfigFileApplicationListener寫的 ,不過這裏實現的功能,其實可以通過 @PropertySource來 解決,只是當時不知道。

使用@PropertySource的話,這麼寫 @PropertySource("file:./download.properties") 即可。

個人猜測SpringBoot從配置中心加載配置就是使用的這個方式,不過由於沒有實際看過相關源碼確認,不敢說一定是的 ,但是應該是八九不離十 的 。

總結

這篇記錄寫的有點亂,一個是涉及到東西感覺也不少,還有就是本身有些地方不怎麼了解,花費的時間不夠。

不過對SpringBoot的外部化配置來說,就是將各個途徑加載進來的配置,統一收歸EnvironmentMutablePropertySources字段,這個字段是一個ArrayList,保持添加進來時的順序,因此查找也是按照這個順序查找,查找時查到即返回,不會完全遍歷所有的配置,除非遇到不存在的。

整個設計思想就是使用集中所有的配置,進行優先級排序,最後在有需要獲取配置的地方,從Environment對象中查找配置項。

對一般使用來說,關注點就是配置文件的位置,配置文件的名,以及優先級,這三個方面比較關心。

這篇記錄也基本能解答這幾個疑問,完成了寫這篇記錄的初衷。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章