Spring Cloud 之 Bootstrap 配置

学习目标

Spring Cloud 之 Bootstrap 配置.png

今天我们一起学习一下 Bootstrap 配置的相关知识,在学习目标中我已经列出了今天需要学习的知识点,第一个知识点为复习知识点,属于 Spring Boot 中的知识,这里我们既然讲到了配置文件,就顺便把 Spring Boot 支持的两种配置文件类型的相关知识复习一下,有助于我们对 Bootstrap 配置的学习。
首先我们先创建项目:打开 https://start.spring.io/,填写相关信息,添加 Web、Actuator 以及 Cloud Bootstrap 依赖,点击 “Generate Project” 按钮生成项目,并导入到 idea 中。(注:此处使用的 Spring Boot 版本为 1.X 系列)

一、(复习)为什么 Spring Boot 可以支持两种配置文件类型

熟悉 Spring Boot 的小伙伴一定知道 Spring Boot 是支持两种配置文件类型的:

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

这里我们通过源代码查找的方式,看一下为什么 Spring Boot 会支持这两种配置文件类型。
首先,我们要找到加载上下文环境的类 **ConfigFileApplicationListener**,这个类是通过加载本地已知的配置文件中的属性来配置上下文环境。
然后在这个类中找到 **Loader#load()**** **方法,查看 **PropertySourcesLoader ** 源码,找到

private final List<PropertySourceLoader> loaders;

这里我们查看一下 **PropertySourceLoader ** 接口的实现类,可以发现,有两个类实现了该接口:

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

具体代码就不再展开讲解了,已经十分明了了。


二、Bootstrap 配置文件

我们都知道,Spring Boot 中使用 application.properties 配置文件,通过上篇文章对 Bootstrap 上下文的学习,我们应该也能猜到,在 Spring Cloud 中使用 bootstrap.properties 配置文件。也就是说,在 Spring Cloud 项目中,application.propertiesbootstrap.properties 配置文件是同时存在的。
**BootstrapApplicationListener#onApplicationEvent()**** **方法中,可以看出当 spring.cloud.bootstrap.name:bootstrap 存在时,使用该配置项,否则,使用 "bootstrap" 默认值。

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

所以我们在项目的 resources 目录下新建名为 bootstrap.properties 的配置文件,这个就是我们 Spring Cloud 中的配置文件。


三、调整 Bootstrap 配置文件名称

由于 Spring Cloud 的默认配置文件为 bootstrap.properties,那如果我们想要修改配置文件的名称应该如何做呢?这里我们使用调整程序启动参数的方式来进行修改。
首先我们在 Idea 中添加如下程序启动参数:

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


bootstrap 配置文件名称发生了改变,改变成了 "spring-cloud",现有三个文件:(标黑的为我们的期望值

  • 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 读取了,这是我们所期望的。
重启项目,在 http://localhost:8080/env 中查看结果,结果也是和我们所期望的是相同的:


四、调整 Bootstrap 配置文件路径

既然配置文件名称是可以修改的,那么接下来我们尝试使用类似的方式修改一下 Bootstrap 配置文件路径,这里我们在 resources 目录下新建 config/spring-cloud2.properties 文件,添加如下程序启动参数:

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


现有四个文件:(标黑的为我们的期望值

  • 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

重启项目,在 http://localhost:8080/env 中查看结果,结果也是和我们所期望的是相同的:


五、自定义 Bootstrap 配置(实现 Spring 标准接口 )

上面说了这么多 Bootstrap 配置相关的东西,一直使用的都是别人的配置项,接下来我们来自定义配置,首先我们实现 Spring 的标准接口来完成自定义Bootstrap 配置 :
1、创建 META-INF/spring.factories 文件(类似于 Spring Boot 自定义 Starter)
2、创建自定义 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();
        // 定义一个新的 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;
    }
}

上面的代码是我们定义了一个新的 PropertySource 并将其放到了 MutablePropertySources 首位,这个配置项的 Key 值是 my-property-source,里面对应的属性信息为 source.put("name", "AlanShelby")
3、配置 META-INF/spring.factories 关联 Key org.springframework.cloud.bootstrap.BootstrapConfiguration

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

然后浏览器访问 http://localhost:8080/env,可以看到以下信息,表示我们自定义的配置成功了:

chapter-6.png


六、自定义 Bootstrap 配置(实现 SpringCloud 的接口)

上面我们使用了实现 Spring 标准接口的方式自定义了 Bootstrap 配置项,接下来我们来实现 Spring Cloud 接口来实现该功能。
1、实现 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 配置属性源(实现 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 关联 Key org.springframework.cloud.bootstrap.BootstrapConfiguration

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

然后浏览器访问 http://localhost:8080/env,可以看到以下信息,表示我们自定义的配置成功了:


至此,关于 Spring Cloud 中的 Bootstrap 配置就讲解完了,这是我的理解,各位看官如果有不同见解或文章中有错误,请不吝指正。
所用代码码云地址:https://gitee.com/AlanShelby/spring-cloud-chapter
知乎专栏地址:https://zhuanlan.zhihu.com/c_200981602
个人微信公众号:AlanShelby(多多关注,感谢~)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,716评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,558评论 1 294
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,431评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,127评论 0 209
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,511评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,692评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,915评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,664评论 0 202
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,412评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,616评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,105评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,424评论 2 254
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,098评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,096评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,869评论 0 197
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,748评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,641评论 2 271