Spring Cloud 之 Bootstrap 配置

學(xué)習(xí)目標(biāo)

Spring Cloud 之 Bootstrap 配置.png

今天我們一起學(xué)習(xí)一下 Bootstrap 配置的相關(guān)知識(shí),在學(xué)習(xí)目標(biāo)中我已經(jīng)列出了今天需要學(xué)習(xí)的知識(shí)點(diǎn),第一個(gè)知識(shí)點(diǎn)為復(fù)習(xí)知識(shí)點(diǎn),屬于 Spring Boot 中的知識(shí),這里我們既然講到了配置文件,就順便把 Spring Boot 支持的兩種配置文件類型的相關(guān)知識(shí)復(fù)習(xí)一下,有助于我們對(duì) Bootstrap 配置的學(xué)習(xí)。
首先我們先創(chuàng)建項(xiàng)目:打開 https://start.spring.io/,填寫相關(guān)信息,添加 Web、Actuator 以及 Cloud Bootstrap 依賴,點(diǎn)擊 “Generate Project” 按鈕生成項(xiàng)目,并導(dǎo)入到 idea 中。(注:此處使用的 Spring Boot 版本為 1.X 系列)

一、(復(fù)習(xí))為什么 Spring Boot 可以支持兩種配置文件類型

熟悉 Spring Boot 的小伙伴一定知道 Spring Boot 是支持兩種配置文件類型的:

  • application.yaml / application.yml
  • application.properties

這里我們通過源代碼查找的方式,看一下為什么 Spring Boot 會(huì)支持這兩種配置文件類型。
首先,我們要找到加載上下文環(huán)境的類 **ConfigFileApplicationListener**,這個(gè)類是通過加載本地已知的配置文件中的屬性來配置上下文環(huán)境。
然后在這個(gè)類中找到 **Loader#load()**** **方法,查看 **PropertySourcesLoader ** 源碼,找到

private final List<PropertySourceLoader> loaders;

這里我們查看一下 **PropertySourceLoader ** 接口的實(shí)現(xiàn)類,可以發(fā)現(xiàn),有兩個(gè)類實(shí)現(xiàn)了該接口:

  • **PropertiesPropertySourceLoader**
  • **YamlPropertySourceLoader**

具體代碼就不再展開講解了,已經(jīng)十分明了了。


二、Bootstrap 配置文件

我們都知道,Spring Boot 中使用 application.properties 配置文件,通過上篇文章對(duì) Bootstrap 上下文的學(xué)習(xí),我們應(yīng)該也能猜到,在 Spring Cloud 中使用 bootstrap.properties 配置文件。也就是說,在 Spring Cloud 項(xiàng)目中,application.propertiesbootstrap.properties 配置文件是同時(shí)存在的。
**BootstrapApplicationListener#onApplicationEvent()**** **方法中,可以看出當(dāng) spring.cloud.bootstrap.name:bootstrap 存在時(shí),使用該配置項(xiàng),否則,使用 "bootstrap" 默認(rèn)值。

String configName = environment.resolvePlaceholders("${spring.cloud.bootstrap.name:bootstrap}");

所以我們?cè)陧?xiàng)目的 resources 目錄下新建名為 bootstrap.properties 的配置文件,這個(gè)就是我們 Spring Cloud 中的配置文件。


三、調(diào)整 Bootstrap 配置文件名稱

由于 Spring Cloud 的默認(rèn)配置文件為 bootstrap.properties,那如果我們想要修改配置文件的名稱應(yīng)該如何做呢?這里我們使用調(diào)整程序啟動(dòng)參數(shù)的方式來進(jìn)行修改。
首先我們?cè)?Idea 中添加如下程序啟動(dòng)參數(shù):

--spring.cloud.bootstrap.name=spring-cloud


bootstrap 配置文件名稱發(fā)生了改變,改變成了 "spring-cloud",現(xiàn)有三個(gè)文件:(標(biāo)黑的為我們的期望值

  • application.properties
    • spring.application.name=spring-cloud-client
  • bootstrap.properties
    • spring.application.name = spring-cloud-config-client-demo
  • spring-cloud.properties
    • spring.application.name = spring-cloud

其中 application.propertiesConfigFileApplicationListener 被加載了)和 spring-cloud.properties 讀取了,這是我們所期望的。
重啟項(xiàng)目,在 http://localhost:8080/env 中查看結(jié)果,結(jié)果也是和我們所期望的是相同的:


四、調(diào)整 Bootstrap 配置文件路徑

既然配置文件名稱是可以修改的,那么接下來我們嘗試使用類似的方式修改一下 Bootstrap 配置文件路徑,這里我們?cè)?resources 目錄下新建 config/spring-cloud2.properties 文件,添加如下程序啟動(dòng)參數(shù):

--spring.cloud.bootstrap.name=spring-cloud2
--spring.cloud.bootstrap.location=config


現(xiàn)有四個(gè)文件:(標(biāo)黑的為我們的期望值

  • application.properties
    • spring.application.name=spring-cloud-client
  • bootstrap.properties
    • spring.application.name = spring-cloud-config-client-demo
  • spring-cloud.properties
    • spring.application.name = spring-cloud
  • config/spring-cloud2.properties
    • spring.application.name = spring-cloud2

重啟項(xiàng)目,在 http://localhost:8080/env 中查看結(jié)果,結(jié)果也是和我們所期望的是相同的:


五、自定義 Bootstrap 配置(實(shí)現(xiàn) Spring 標(biāo)準(zhǔn)接口 )

上面說了這么多 Bootstrap 配置相關(guān)的東西,一直使用的都是別人的配置項(xiàng),接下來我們來自定義配置,首先我們實(shí)現(xiàn) Spring 的標(biāo)準(zhǔn)接口來完成自定義Bootstrap 配置 :
1、創(chuàng)建 META-INF/spring.factories 文件(類似于 Spring Boot 自定義 Starter)
2、創(chuàng)建自定義 Bootstrap 配置 Configuration

package top.alanshelby.springcloudchapter2.bootstrap;

import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertySource;

import java.util.HashMap;
import java.util.Map;

/**
 * Bootstrap 配置 Bean
 *
 * @ClassName MyConfiguration
 * @Author AlanShelby
 * @Date 2019-04-22 14:29:14 14:29
 * @Version 1.0
 */
@Configuration
public class MyConfiguration implements ApplicationContextInitializer {

    @Override
    public void initialize(ConfigurableApplicationContext applicationContext) {
        ConfigurableEnvironment environment = applicationContext.getEnvironment();
        // 獲取 PropertySource
        MutablePropertySources propertySources = environment.getPropertySources();
        // 定義一個(gè)新的 PropertySource 放在首位
        propertySources.addFirst(createPropertySource());
    }

    private PropertySource createPropertySource() {
        Map<String, Object> source = new HashMap<>();
        source.put("name", "AlanShelby");

        PropertySource propertySource = new MapPropertySource("my-property-source", source);

        return propertySource;
    }
}

上面的代碼是我們定義了一個(gè)新的 PropertySource 并將其放到了 MutablePropertySources 首位,這個(gè)配置項(xiàng)的 Key 值是 my-property-source,里面對(duì)應(yīng)的屬性信息為 source.put("name", "AlanShelby")
3、配置 META-INF/spring.factories 關(guān)聯(lián) Key org.springframework.cloud.bootstrap.BootstrapConfiguration

org.springframework.cloud.bootstrap.BootstrapConfiguration =top.alanshelby.springcloudchapter2.bootstrap.MyConfiguration

然后瀏覽器訪問 http://localhost:8080/env,可以看到以下信息,表示我們自定義的配置成功了:

chapter-6.png


六、自定義 Bootstrap 配置(實(shí)現(xiàn) SpringCloud 的接口)

上面我們使用了實(shí)現(xiàn) Spring 標(biāo)準(zhǔn)接口的方式自定義了 Bootstrap 配置項(xiàng),接下來我們來實(shí)現(xiàn) Spring Cloud 接口來實(shí)現(xiàn)該功能。
1、實(shí)現(xiàn) PropertySourceLocator

package top.alanshelby.springcloudchapter2;

import org.springframework.cloud.bootstrap.config.PropertySourceLocator;
import org.springframework.core.env.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 自定義 Bootstrap 配置屬性源(實(shí)現(xiàn) SpringCloud 的接口)
 *
 * @ClassName MyPropertySourceLocator
 * @Author AlanShelby
 * @Date 2019-04-22 14:45:15 14:45
 * @Version 1.0
 */
public class MyPropertySourceLocator implements PropertySourceLocator {
    @Override
    public PropertySource<?> locate(Environment environment) {
        if (environment instanceof ConfigurableEnvironment) {
            ConfigurableEnvironment configurableEnvironment = ConfigurableEnvironment.class.cast(environment);
            MutablePropertySources propertySources = configurableEnvironment.getPropertySources();
            propertySources.addFirst(createPropertySource());
        }
        return null;
    }

    private PropertySource createPropertySource() {
        Map<String, Object> source = new HashMap<>();
        source.put("spring.application.name", "AlanShelby-SpringCloud");
   
        PropertySource propertySource = new MapPropertySource("alan-property-source", source);

        return propertySource;
    }
}

2、配置 META-INF/spring.factories 關(guān)聯(lián) Key org.springframework.cloud.bootstrap.BootstrapConfiguration

org.springframework.cloud.bootstrap.BootstrapConfiguration = top.alanshelby.springcloudchapter2.MyPropertySourceLocator

然后瀏覽器訪問 http://localhost:8080/env,可以看到以下信息,表示我們自定義的配置成功了:


至此,關(guān)于 Spring Cloud 中的 Bootstrap 配置就講解完了,這是我的理解,各位看官如果有不同見解或文章中有錯(cuò)誤,請(qǐng)不吝指正。
所用代碼碼云地址:https://gitee.com/AlanShelby/spring-cloud-chapter
知乎專欄地址:https://zhuanlan.zhihu.com/c_200981602
個(gè)人微信公眾號(hào):AlanShelby(多多關(guān)注,感謝~)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容