目錄
- 前言
- 1. Spring Cloud 什么時候加載組態檔
- 2. 準備 Environment 配置環境
- 2.1 配置 Environment 環境 SpringApplication.prepareEnvironment()
- 2.2 使用事件主控器創建并發布事件 SimpleApplicationEventMulticaster.multicastEvent()
- 2.3 BootstrapApplicationListener 處理事件,自動匯入一些配置類
- 3. 重繪應用背景關系
- 3.1 重繪背景關系 SpringApplication.prepareContext()
- 3.2 初始化背景關系的額外操作 SpringApplication.applyInitializers()
- 3.3 讀取 Nacos 服務器里的配置 NacosPropertySourceLocator.locate()
- 3.4 初始化完成,發布 ApplicationContextInitializedEvent 事件
- 3.5 配置加載完成,將監聽器添加進背景關系環境
- 4. 程式運行事件
- 5. Spring Cloud 啟動及加載組態檔原始碼結構圖小結
- 最后
前言
參考資料:
《Spring Microservices in Action》
《Spring Cloud Alibaba 微服務原理與實戰》
《B站 尚硅谷 SpringCloud 框架開發教程 周陽》
Spring Cloud 要實作統一配置管理,需要解決兩個問題:如何獲取遠程服務器配置和如何動態更新配置;在這之前,我們先要知道 Spring Cloud 什么時候給我們加載組態檔;
1. Spring Cloud 什么時候加載組態檔
- 首先,Spring 抽象了一個 Environment 來表示 Spring 應用程式環境配置,整合了各種各樣的外部環境,并且提供統一訪問的方法
getProperty(); - 在 Spring 應用程式啟動時,會把配置加載到 Environment 中,當創建一個 Bean 時可以從 Environment 中把一些屬性值通過
@Value的形式注入業務代碼; - Spring Cloud 是基于 Spring 的發展而來,因此也是在啟動時加載組態檔,而 Spring Cloud 的啟動程式是主程式類 XxxApplication,我們斷點進入主程式類;
@EnableDiscoveryClient
@SpringBootApplication
public class ProviderApplication {
public static void main(String[] args) {
//【斷點步入】主啟動方法
SpringApplication.run(ProviderApplication.class, args);
}
}
- 在
SpringApplication.run()運行方法里會準備 Environment 環境;
public ConfigurableApplicationContext run(String... args) {
//初始化StopWatch,呼叫 start 方法開始計時
StopWatch stopWatch = new StopWatch();
stopWatch.start();
ConfigurableApplicationContext context = null;
Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList();
//設定系統屬性java.awt.headless,這里為true,表示運行在服務器端,在沒有顯示幕和滑鼠鍵盤的模式下作業,模擬輸入輸出設備功能
this.configureHeadlessProperty();
SpringApplicationRunListeners listeners = this.getRunListeners(args);
//SpringApplicationRunListeners 監聽器作業--->發布 ApplicationStartingEvent 事件
listeners.starting();
Collection exceptionReporters;
try {
//持有著 args 引數
ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
//【斷點步入 2.】準備 Environment 環境--->發布 ApplicationEnvironmentPreparedEvent 事件
ConfigurableEnvironment environment = this.prepareEnvironment(listeners, applicationArguments);
this.configureIgnoreBeanInfo(environment);
//列印 banner
Banner printedBanner = this.printBanner(environment);
//創建 SpringBoot 背景關系
context = this.createApplicationContext();
exceptionReporters = this.getSpringFactoriesInstances(SpringBootExceptionReporter.class, new Class[]{ConfigurableApplicationContext.class}, context);
//【斷點步入 3.】準備應用背景關系--->發布 ApplicationEnvironmentPreparedEvent 事件
this.prepareContext(context, environment, listeners, applicationArguments, printedBanner);
//重繪背景關系--->發布 ContextRefreshedEvent 事件
this.refreshContext(context);
//在容器完成重繪后,依次呼叫注冊的Runners
this.afterRefresh(context, applicationArguments);
//停止計時
stopWatch.stop();
if (this.logStartupInfo) {
(new StartupInfoLogger(this.mainApplicationClass)).logStarted(this.getApplicationLog(), stopWatch);
}
//SpringApplicationRunListeners 監聽器作業--->發布 ApplicationStartedEvent 事件
listeners.started(context);
this.callRunners(context, applicationArguments);
} catch (Throwable var10) {
this.handleRunFailure(context, var10, exceptionReporters, listeners);
throw new IllegalStateException(var10);
}
try {
//【斷點步入 4.】SpringApplicationRunListeners 監聽程式運行事件--->發布ApplicationReadyEvent事件
listeners.running(context);
return context;
} catch (Throwable var9) {
this.handleRunFailure(context, var9, exceptionReporters, (SpringApplicationRunListeners)null);
throw new IllegalStateException(var9);
}
}
- 注意,有些同學可能 debug 進不了這里的 try 陳述句,可能是因為引入了以下這個依賴,去掉這個依賴即可;
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
2. 準備 Environment 配置環境
2.1 配置 Environment 環境 SpringApplication.prepareEnvironment()
- 我們進入
SpringApplication.prepareEnvironment()方法里,該方法主要是根據一些資訊配置 Environment 環境,然后呼叫 SpringApplicationRunListeners(Spring 應用運行監聽器) 監聽器作業;
private ConfigurableEnvironment prepareEnvironment(SpringApplicationRunListeners listeners, ApplicationArguments applicationArguments) {
//獲取可配置的環境
ConfigurableEnvironment environment = this.getOrCreateEnvironment();
//根據可配置的環境,配置 Environment 環境
this.configureEnvironment((ConfigurableEnvironment)environment, applicationArguments.getSourceArgs());
//【斷點步入】告訴監聽者 Environment 環境已經準備完畢
listeners.environmentPrepared((ConfigurableEnvironment)environment);
this.bindToSpringApplication((ConfigurableEnvironment)environment);
if (!this.isCustomEnvironment) {
environment = (new EnvironmentConverter(this.getClassLoader())).convertEnvironmentIfNecessary((ConfigurableEnvironment)environment, this.deduceEnvironmentClass());
}
- 進入
SpringApplicationRunListeners.environmentPrepared()方法,該方法的作用是遍歷每一個監聽者,并對這些監聽者進行操作;
public void environmentPrepared(ConfigurableEnvironment environment) {
//使用迭代器遍歷監聽者
Iterator var2 = this.listeners.iterator();
while(var2.hasNext()) {
SpringApplicationRunListener listener = (SpringApplicationRunListener)var2.next();
//【斷點步入】對每一個監聽者進行操作
listener.environmentPrepared(environment);
}
}
2.2 使用事件主控器創建并發布事件 SimpleApplicationEventMulticaster.multicastEvent()
- 進入
EventPublishingRunListener.environmentPrepared()方法,發現對每一個監聽者實作的操作是:使用 SimpleApplicationEventMulticaster(事件主控器) 發布了一個 ApplicationEnvironmentPreparedEvent(應用程式環境準備完成事件);
public void environmentPrepared(ConfigurableEnvironment environment) {
//【斷點步入】使用事件主控器發布事件
this.initialMulticaster.multicastEvent(new ApplicationEnvironmentPreparedEvent(this.application, this.args, environment));
}
- 進入
SimpleApplicationEventMulticaster.multicastEvent()方法
public void multicastEvent(ApplicationEvent event, @Nullable ResolvableType eventType) {
//決議出事件型別
ResolvableType type = eventType != null ? eventType : this.resolveDefaultEventType(event);
//獲得事件執行者
Executor executor = this.getTaskExecutor();
//獲得監聽者迭代器
Iterator var5 = this.getApplicationListeners(event, type).iterator();
while(var5.hasNext()) {
ApplicationListener<?> listener = (ApplicationListener)var5.next();
//如果有執行者,就通過執行者發布事件
if (executor != null) {
executor.execute(() -> {
this.invokeListener(listener, event);
});
} else {
//【斷點步入 1.2】沒有執行者就直接發事件
this.invokeListener(listener, event);
}
}
}
- 總結來說就是 Spring Cloud 在配置完 Environment 環境后會發布一個 ApplicationEnvironmentPreparedEvent(應用程式環境準備完成事件) 告訴所有監聽者,Environment 環境已經配置完畢了;
- 所有對 ApplicationEnvironmentPreparedEvent 事件感興趣的 Listener 都會監聽這個事件,其中包括 BootstrapApplicationListener;

- 注意,這里需要遍歷到后面才是 ApplicationEnvironmentPreparedEvent 事件,前面可能是其他事件;
2.3 BootstrapApplicationListener 處理事件,自動匯入一些配置類
- 發布事件后被 BootstrapApplicationListener(Bootstrap 監聽器) 監聽到,呼叫
BootstrapApplicationListener.onApplicationEvent()方法處理事件:
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
//獲取當前 Environment 環境
ConfigurableEnvironment environment = event.getEnvironment();
//如果環境可用
if ((Boolean)environment.getProperty("spring.cloud.bootstrap.enabled", Boolean.class, true)) {
//如果環境來源不包含 bootstrap
if (!environment.getPropertySources().contains("bootstrap")) {
ConfigurableApplicationContext context = null;
String configName = environment.resolvePlaceholders("${spring.cloud.bootstrap.name:bootstrap}");
Iterator var5 = event.getSpringApplication().getInitializers().iterator();
while(var5.hasNext()) {
ApplicationContextInitializer<?> initializer = (ApplicationContextInitializer)var5.next();
if (initializer instanceof ParentContextApplicationContextInitializer) {
context = this.findBootstrapContext((ParentContextApplicationContextInitializer)initializer, configName);
}
}
if (context == null) {
//【斷點步入】將不是 bootstrap 來源的配置添加進 bootstrap 背景關系
context = this.bootstrapServiceContext(environment, event.getSpringApplication(), configName);
event.getSpringApplication().addListeners(new ApplicationListener[]{new BootstrapApplicationListener.CloseContextOnFailureApplicationListener(context)});
}
this.apply(context, event.getSpringApplication(), environment);
}
}
}
- 進入
BootstrapApplicationListener.bootstrapServiceContext()方法,發現其主要做的是配置自動匯入的實作;
private ConfigurableApplicationContext bootstrapServiceContext(ConfigurableEnvironment environment, final SpringApplication application, String configName) {
//省略其他代碼
//配置自動裝配的實作
builder.sources(new Class[]{BootstrapImportSelectorConfiguration.class});
return context;
}
- 我們搜索 BootstrapImportSelectorConfiguration(Bootstrap選擇匯入配置類) 類,發現其使用 BootstrapImportSelector(Bootstrap匯入選擇器) 進行自動配置;
@Configuration
@Import({BootstrapImportSelector.class}) //使用BootstrapImportSelector類進行自動配置
public class BootstrapImportSelectorConfiguration {
public BootstrapImportSelectorConfiguration() {
}
}
- BootstrapImportSelector(Bootstrap 匯入選擇器) 類的
selectImports()方法使用 Spring 中的 SPI 機制;
public String[] selectImports(AnnotationMetadata annotationMetadata) {
//省略其他代碼
List<String> names = new ArrayList(SpringFactoriesLoader.loadFactoryNames(BootstrapConfiguration.class, classLoader));
}
- 可到 classpath 路徑下查找 META-INF/spring.factories 預定義的一些擴展點,其中 key 為 BootstrapConfiguration;
- 可以得知給我們匯入了一些,其中有兩個配置類 PropertySourceBootstrapConfiguration 和 NacosConfigBootstrapConfiguration(這兩個類在本篇 3.2 和 3.3 里會提到,用來加載額外配置的);
3. 重繪應用背景關系
3.1 重繪背景關系 SpringApplication.prepareContext()
- 我們回到
SpringApplication.run()方法里,在準備完 Environment 環境后,會呼叫SpringApplication.prepareContext()方法重繪應用背景關系,我們進入該方法;
private void prepareContext(ConfigurableApplicationContext context, ConfigurableEnvironment environment, SpringApplicationRunListeners listeners, ApplicationArguments applicationArguments, Banner printedBanner) {
//設定背景關系的 Environment 環境
context.setEnvironment(environment);
this.postProcessApplicationContext(context);
//【斷點步入 3.2】初始化背景關系
this.applyInitializers(context);
//【斷點步入 3.4】發布背景關系初始化完畢事件 ApplicationContextInitializedEvent
listeners.contextPrepared(context);
//后面代碼省略
//【斷點步入 3.5】這是該方法的最后一條陳述句,發布
listeners.contextLoaded(context);
}
3.2 初始化背景關系的額外操作 SpringApplication.applyInitializers()
- 進入
SpringApplication.applyInitializers()方法,在應用程式背景關系初始化時做一些額外操作; - 即執行非 Spring Cloud 官方提供的額外的操作,這里指 Nacos 自己的操作;
protected void applyInitializers(ConfigurableApplicationContext context) {
Iterator var2 = this.getInitializers().iterator();
while(var2.hasNext()) {
ApplicationContextInitializer initializer = (ApplicationContextInitializer)var2.next();
Class<?> requiredType = GenericTypeResolver.resolveTypeArgument(initializer.getClass(), ApplicationContextInitializer.class);
Assert.isInstanceOf(requiredType, context, "Unable to call initializer.");
//【斷點步入】遍歷迭代器,初始化背景關系
initializer.initialize(context);
}
}
- 這里的
.initialize()方法最終呼叫的是 PropertySourceBootstrapConfiguration(Bootstrap 屬性源配置類) ,而這個類就是 1.2 里準備 Environment 環境時給我們自動匯入的,我們進入PropertySourceBootstrapConfiguration.initialize()方法,得出最后結論:
public void initialize(ConfigurableApplicationContext applicationContext) {
//省略其他代碼
Iterator var5 = this.propertySourceLocators.iterator();
while(var5.hasNext()) {
//PropertySourceLocator 介面的主要作用是實作應用外部化配置可動態加載
PropertySourceLocator locator = (PropertySourceLocator)var5.next();
PropertySource<?> source = null;
//【斷點步入】讀取 Nacos 服務器里的配置
source = locator.locate(environment);
}
}
3.3 讀取 Nacos 服務器里的配置 NacosPropertySourceLocator.locate()
- 我們 1.2 里準備的 Environment 環境中引入的配置類 NacosPropertySourceLocator 實作了該介面,因此最后呼叫的是
NacosPropertySourceLocator.locate()方法; - 該方法將讀取 Nacos 服務器里的配置,把結構存到 PropertySource 的實體里回傳;
NacosPropertySourceLocator.locate()方法原始碼如下:
@Override
public PropertySource<?> locate(Environment env) {
//獲取配置服務器實體,這是Nacos客戶端提供的用于訪問實作配置中心基本操作的類
ConfigService configService = nacosConfigProperties.configServiceInstance();
if (null == configService) {
log.warn("no instance of config service found, can't load config from nacos");
return null;
}
long timeout = nacosConfigProperties.getTimeout();
//Nacos 屬性源生成器
nacosPropertySourceBuilder = new NacosPropertySourceBuilder(configService, timeout);
String name = nacosConfigProperties.getName();
//DataId 前綴
String dataIdPrefix = nacosConfigProperties.getPrefix();
if (StringUtils.isEmpty(dataIdPrefix)) {
dataIdPrefix = name;
}
//沒有配置 DataId 前綴則用 spring.application.name 屬性的值
if (StringUtils.isEmpty(dataIdPrefix)) {
dataIdPrefix = env.getProperty("spring.application.name");
}
//創建復合屬性源
CompositePropertySource composite = new CompositePropertySource(NACOS_PROPERTY_SOURCE_NAME);
//加載共享配置
loadSharedConfiguration(composite);
//加載外部配置
loadExtConfiguration(composite);
//加載 Nacos 服務器上應用程式名對應的的配置
loadApplicationConfiguration(composite, dataIdPrefix, nacosConfigProperties, env);
return composite;
}
3.4 初始化完成,發布 ApplicationContextInitializedEvent 事件
- 進入
SpringApplicationRunListeners.contextPrepared()發布事件;
public void contextPrepared(ConfigurableApplicationContext context) {
//構造迭代器
Iterator var2 = this.listeners.iterator();
while(var2.hasNext()) {
SpringApplicationRunListener listener = (SpringApplicationRunListener)var2.next();
//【斷點步入】發布事件
listener.contextPrepared(context);
}
}
- 進入
EventPublishingRunListener.contextPrepared(),通過 multicastEvent 發布事件;
public void contextPrepared(ConfigurableApplicationContext context) {
//發布 ApplicationContextInitializedEvent 事件
this.initialMulticaster.multicastEvent(new ApplicationContextInitializedEvent(this.application, this.args, context));
}
3.5 配置加載完成,將監聽器添加進背景關系環境
- 注意與 3.4 里的方法不同;
- 進入
SpringApplicationRunListeners.contextLoaded()配置加載完成;
public void contextLoaded(ConfigurableApplicationContext context) {
Iterator var2 = this.listeners.iterator();
while(var2.hasNext()) {
SpringApplicationRunListener listener = (SpringApplicationRunListener)var2.next();
//【斷點步入】
listener.contextLoaded(context);
}
}
- 進入
EventPublishingRunListener.contextLoaded()將監聽器添加進背景關系環境;
public void contextLoaded(ConfigurableApplicationContext context) {
ApplicationListener listener;
//遍歷每一個監聽器(一共有13個,如下圖),將除最后一個監聽器外的監聽器添加進 context 背景關系
for(Iterator var2 = this.application.getListeners().iterator(); var2.hasNext(); context.addApplicationListener(listener)) {
listener = (ApplicationListener)var2.next();
if (listener instanceof ApplicationContextAware) {
//第10個 ParentContextCloseApplicationListener 會進來
((ApplicationContextAware)listener).setApplicationContext(context);
}
}
//發布 ApplicationPreparedEvent 事件
this.initialMulticaster.multicastEvent(new ApplicationPreparedEvent(this.application, this.args, context));
}

4. 程式運行事件
- 進入
SpringApplicationRunListeners.running()方法,它對每一個監聽器操作;
public void running(ConfigurableApplicationContext context) {
Iterator var2 = this.listeners.iterator();
while(var2.hasNext()) {
SpringApplicationRunListener listener = (SpringApplicationRunListener)var2.next();
//【斷點步入】操作監聽器,其中就有 EventPublishingRunListener
listener.running(context);
}
}
- 進入
EventPublishingRunListener.running()方法,發布 ApplicationReadyEvent 事件;
public void running(ConfigurableApplicationContext context) {
context.publishEvent(new ApplicationReadyEvent(this.application, this.args, context));
}
5. Spring Cloud 啟動及加載組態檔原始碼結構圖小結
- SpringApplication.run():加載配置背景關系;
- stopWatch.start():初始化StopWatch,呼叫 start 方法開始計時;
- SpringApplicationRunListeners.starting():發布
ApplicationStartingEvent事件; - SpringApplication.prepareEnvironment():準備 Environment 環境;
- SpringApplicationRunListeners.environmentPrepared():監聽環境準備事件;
- EventPublishingRunListener.environmentPrepared():對每一個進行操作;
- SimpleApplicationEventMulticaster.multicastEvent():使用事件主控器發布
ApplicationEnvironmentPreparedEvent事件; - BootstrapApplicationListener.onApplicationEvent():bootstrap 監聽器處理事件;
- BootstrapApplicationListener.bootstrapServiceContext():給我們自動匯入一些配置類;
- SimpleApplicationEventMulticaster.multicastEvent():使用事件主控器發布
- EventPublishingRunListener.environmentPrepared():對每一個進行操作;
- SpringApplicationRunListeners.environmentPrepared():監聽環境準備事件;
- SpringApplication.printBanner():列印 Banner;
- printBanner.createApplicationContext():創建 Spring Boot 背景關系;
- SpringApplication.prepareContext():重繪應用背景關系;
- SpringApplication.applyInitializers():初始化背景關系的額外操作;
- PropertySourceBootstrapConfiguration.initialize():外部化配置;
- NacosPropertySourceLocator.locate():讀取 Nacos 服務器里的配置;
- PropertySourceBootstrapConfiguration.initialize():外部化配置;
- SpringApplicationRunListeners.contextPrepared():配置初始化完成;
- EventPublishingRunListener.contextPrepared():發布
ApplicationContextInitializedEvent事件;
- EventPublishingRunListener.contextPrepared():發布
- SpringApplicationRunListeners.contextPrepared():配置加載完成
- EventPublishingRunListener.contextLoaded():將監聽器添加進背景關系環境;
- SpringApplication.applyInitializers():初始化背景關系的額外操作;
- StopWatch.stop():停止計時;
- SpringApplicationRunListeners.started():發布 ApplicationStartedEvent 事件;
- SpringApplicationRunListeners.running():監聽程式運行事件;
- EventPublishingRunListener.running():發布
ApplicationReadyEvent事件;
- EventPublishingRunListener.running():發布
最后

轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/419946.html
標籤:其他
上一篇:微服務架構 | *2.4 Nacos 獲取配置與事件訂閱機制的原始碼分析
下一篇:Mssql錯誤:選擇串列中的列'dbo.History.Email'無效,因為它既不包含在聚合函式中,也不包含在GROUPBY子句中
