天天看點

SpringBoot外部化配置使用Plus版

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中,并将檔案放置于以下四個位置即可 。

位于jar同目錄的config目錄下的application.properties

位于jar同目錄的application.properties

classpath下的config内application.properties

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,那麼結果會是dev和test都會存在,而不是替換的行為 。

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

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

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

propery source#

注解@PropertySource可以寫在配置類上,并且指定要讀取的配置檔案路徑,這個路徑可以是絕對路徑,也可以是相對路徑。

它可以有以下幾種配置

@PropertySource("/config.properties")

@PropertySource("config.properties")

@PropertySource("file:/usr/local/config.properties")

@PropertySource("file:./config.properties")

@PropertySource("${pathPrefix}/config.properties")

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

3和4是使用檔案系統的絕對和相對路徑的方式,這裡絕對路徑比較好了解 ,相對路徑則是從項目的根目錄作為相對目錄的

5是結合SpEL的表達式來使用的,可以直接從環境中擷取配置好的路徑。

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

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

原理淺入淺出#

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

是以這裡描述幾個會引起疑問的現象

預設情況下自動加載的配置檔案命名必須要是application

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

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

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

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

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

源碼簡讀#

SpringBoot讀取application.properties配置

檢視org.springframework.boot.context.config.ConfigFileApplicationListener的源碼

Copy

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

從上面可以看出處理@ConfigurationProperty的BeanPostProcessor優先級很高,而@Value的BeanPostProcessor優先級很低。

使用@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的外部化配置來說,就是将各個途徑加載進來的配置,統一收歸Environment的MutablePropertySources字段,這個字段是一個ArrayList,保持添加進來時的順序,是以查找也是按照這個順序查找,查找時查到即傳回,不會完全周遊所有的配置,除非遇到不存在的。

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

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

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

作者: 早知今日

出處:

https://www.cnblogs.com/heartlake/p/12967231.html