簡介:前端
1、SpringBoot特徵:java
2、SpringBoot版本:web
CURRENT: 當前最新版本redis
GA:General Availability,正式發佈的版本,官方推薦使用此版本。在國外都是用GA來講明release版本的。spring
PRE: 預覽版,內部測試版. 主要是給開發人員和測試人員測試和找BUG用的,不建議使用;apache
SNAPSHOT: 快照版,能夠穩定使用,且仍在繼續改進版本。api
3、SpringBoot application starters:數組
Springboot提供了一些主流的整合包以下,可是一些非主流的整合就由整合方本身提供,例如springboot和dubbo的整合是由apache提供整合包。springboot
4、Dubbo背景:markdown
單一應用架構
當網站流量很小時,只需一個應用,將全部功能都部署在一塊兒,以減小部署節點和成本。此時,用於簡化增刪改查工做量的數據訪問框架(ORM)是關鍵。
垂直應用架構
當訪問量逐漸增大,單一應用增長機器帶來的加速度愈來愈小,將應用拆成互不相干的幾個應用,以提高效率。此時,用於加速前端頁面開發的Web框架(MVC)是關鍵。
分佈式服務架構
當垂直應用愈來愈多,應用之間交互不可避免,將核心業務抽取出來,做爲獨立的服務,逐漸造成穩定的服務中心,使前端應用能更快速的響應多變的市場需求。此時,用於提升業務複用及整合的分佈式服務框架(RPC)是關鍵。
流動計算架構
當服務愈來愈多,容量的評估,小服務資源的浪費等問題逐漸顯現,此時需增長一個調度中心基於訪問壓力實時管理集羣容量,提升集羣利用率。此時,用於提升機器利用率的資源調度和治理中心(SOA)是關鍵。
5、SpringBoot整合Dubbo:
參考文檔1:com.alibaba
參考文檔2:apache dubbo
SpringBoot整合dubbo版本要求:
Dubbo Spring Boot Dubbo Spring Boot 0.2.1.RELEASE 2.6.5+ 2.x
0.1.2.RELEASE 2.6.5+ 1.x
步驟一:建立一個項目boot-dubbo,在父模塊pom.xml引入基本配置
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.clinks</groupId>
<artifactId>boot-dubbo-parent</artifactId>
<version>1.0-SNAPSHOT</version>
<!-- 在這裏設置打包類型爲pom,做用是爲了實現多模塊項目 -->
<packaging>pom</packaging>
<!-- 第一步:添加Springboot的parent -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.9.RELEASE</version>
</parent>
<modules>
<module>../boot-dubbo-dl</module>
<module>../boot-dubbo-service</module>
<module>../boot-dubbo-web</module>
</modules>
<!-- 版本屬性 -->
<properties>
<!--springBoot整合dubbo依賴-->
<dubbo.boot.version>0.2.1.RELEASE</dubbo.boot.version>
<dubbo.version>2.6.5</dubbo.version>
</properties>
</project>
複製代碼
步驟二:建立三個子模塊:boot-dubbo-api、boot-dubbo-provider、boot-dubbo-web
boot-dubbo-api做爲接口模塊,打成jar包可被另外兩個模塊引用,全部的服務接口聲明均可寫在該模塊;
boot-dubbo-provider做爲服務提供方,接口實現類可寫在該模塊,並被註冊到註冊中心,可供其餘模塊調用;
boot-dubbo-web做爲服務消費方,能夠rpc遠程調用服務。
步驟三:boot-dubbo-dl部分pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>boot-dubbo-dl</artifactId>
<packaging>jar</packaging>
<parent>
<artifactId>boot-dubbo-parent</artifactId>
<groupId>com.clinks</groupId>
<version>1.0-SNAPSHOT</version>
<relativePath>../boot-dubbo-parent/pom.xml</relativePath>
</parent>
<dependencies>
<!-- jar依賴 -->
<dependency>
<groupId>com.clinks</groupId>
<artifactId>boot-dubbo-service</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<!-- 核心SpringBoot-starter依賴 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<!-- springBoot-dubbo依賴 -->
<dependency>
<groupId>com.alibaba.boot</groupId>
<artifactId>dubbo-spring-boot-starter</artifactId>
<version>${dubbo.boot.version}</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>dubbo</artifactId>
<version>${dubbo.version}</version>
</dependency>
<!--使用redis作註冊中心-->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
</dependencies>
</project>
複製代碼
步驟4、配置文件
----xml方式----
<dubbo:application name="agent-hr-dl"/>
<dubbo:registry address="${dubbo.address}" username="test" password="${redis.password}"/>
<dubbo:consumer retries="0" filter="cat_filter"/>
<dubbo:service interface="com.clinks.agent.hr.service.IAgentKpiService" ref="agentKpiServiceImpl"/>
----註解方式----
dubbo.application.name=dubbo-consumer-annotation
dubbo.registry.address=redis://139.196.28.237:6641
dubbo.registry.username=test
dubbo.registry.password=Toodc600
dubbo.consumer.timeout=3000
dubbo.consumer.registries=0
---javaConfig方式
複製代碼
步驟五:核心啓動類Application
@SpringBootApplication
@EnableDubbo
public class ProviderApplication {
public static void main(String[] args) {
SpringApplication.run(ProviderApplication.class, args);
}
}
複製代碼
步驟六:boot-dubbo-web部分pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.clinks</groupId>
<artifactId>boot-dubbo-parent</artifactId>
<version>1.0-SNAPSHOT</version>
<relativePath>../boot-dubbo-parent</relativePath>
</parent>
<groupId>com.clinks</groupId>
<artifactId>boot-dubbo-web</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<!-- jar依賴 -->
<dependency>
<groupId>com.clinks</groupId>
<artifactId>boot-dubbo-service</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<!-- 核心SpringBoot-starter依賴 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<!-- springBoot-dubbo依賴 -->
<dependency>
<groupId>com.alibaba.boot</groupId>
<artifactId>dubbo-spring-boot-starter</artifactId>
<version>${dubbo.boot.version}</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>dubbo</artifactId>
<version>${dubbo.version}</version>
</dependency>
<!--web模塊-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--test模塊-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<!--redis-->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
</dependencies>
</project>
複製代碼
6、核心註解篇
註解一:@SpringBootApplication:**
組合註解:
@Configuration :是一個類註解,標明這是一個配置類,將啓動類聲明成一個配置類
通常與@Bean合用,做用至關於
@ComponentScan :指定掃描包
Springboot默認掃描同包以及子包下註解,如@Controller,@Service,@Configuration
@EnableAutoConfiguration : 開啓 Spring 應用程序上下文的自動配置
原理簡單說明:
註解二:@EnableDubbo
註解3、@Service
經過 @Service 上提供的屬性,能夠進一步的定製化 Dubbo 的服務提供方:
package org.apache.dubbo.config.annotation;
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE}) // #1
@Inherited
public @interface Service {
Class<?> interfaceClass() default void.class; // #2
String interfaceName() default ""; // #3
String version() default ""; // #4
String group() default ""; // #5
boolean export() default true; // #6
boolean register() default true; // #7
String application() default ""; // #8
String module() default ""; // #9
String provider() default ""; // #10
String[] protocol() default {}; // #11
String monitor() default ""; // #12
String[] registry() default {}; // #13
}
複製代碼
其中比較重要的有:
註解4、@Reference
經過 @Reference 上提供的屬性,能夠進一步的定製化 Dubbo 的服務消費方:
package org.apache.dubbo.config.annotation;
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.ANNOTATION_TYPE}) // #1
public @interface Reference {
Class<?> interfaceClass() default void.class; // #2
String interfaceName() default ""; // #3
String version() default ""; // #4
String group() default ""; // #5
String url() default ""; // #6
String application() default ""; // #7
String module() default ""; // #8
String consumer() default ""; // #9
String protocol() default ""; // #10
String monitor() default ""; // #11
String[] registry() default {}; // #12
}
複製代碼
其中比較重要的有:
7、SpringBoot源碼解析
啓動流程:
一、建立SpringApplication對象
initialize(sources);
private void initialize(Object[] sources) {
//保存主配置類
if (sources != null && sources.length > 0) { this.sources.addAll(Arrays.asList(sources));
}
//判斷當前是否一個web應用
this.webEnvironment = deduceWebEnvironment();
//從類路徑下找到META‐INF/spring.factories配置的全部ApplicationContextInitializer;而後保存起來
setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class);
//從類路徑下找到ETA‐INF/spring.factories配置的全部ApplicationListener
setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
//從多個配置類中找到有main方法的主配置類
this.mainApplicationClass = deduceMainApplicationClass();
}
複製代碼
二、運行run()方法
public ConfigurableApplicationContext run(String... args) { StopWatch stopWatch = new StopWatch();
stopWatch.start();
ConfigurableApplicationContext context = null;
FailureAnalyzers analyzers = null;
configureHeadlessProperty();
//獲取SpringApplicationRunListeners;從類路徑下META‐INF/spring.factories
SpringApplicationRunListeners listeners = getRunListeners(args);
//回調全部的獲取SpringApplicationRunListener.starting()方法
listeners.starting();
try {
//封裝命令行參數
ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
//準備環境
ConfigurableEnvironment environment = prepareEnvironment(listeners,applicationArguments);
//建立環境完成後回調SpringApplicationRunListener.environmentPrepared();表示環境準備完成
Banner printedBanner = printBanner(environment);
//建立ApplicationContext;決定建立web的ioc仍是普通的ioc
context = createApplicationContext(); analyzers = new FailureAnalyzers(context);
//準備上下文環境;將environment保存到ioc中;並且applyInitializers(); //applyInitializers():回調以前保存的全部的ApplicationContextInitializer的initialize方法 //回調全部的SpringApplicationRunListener的contextPrepared();
prepareContext(context, environment, listeners, applicationArguments, printedBanner);
//prepareContext運行完成之後回調全部的SpringApplicationRunListener的contextLoaded();
//刷新容器;ioc容器初始化(若是是web應用還會建立嵌入式的Tomcat);Spring註解版
//掃描,建立,加載全部組件的地方;(配置類,組件,自動配置)
refreshContext(context);
//從ioc容器中獲取全部的ApplicationRunner和CommandLineRunner進行回調 //ApplicationRunner先回調,CommandLineRunner再回調
afterRefresh(context, applicationArguments);
//全部的SpringApplicationRunListener回調finished方法
listeners.finished(context, null);
stopWatch.stop();
if (this.logStartupInfo) {
new StartupInfoLogger(this.mainApplicationClass) .logStarted(getApplicationLog(), stopWatch);
}
//整個SpringBoot應用啓動完成之後返回啓動的ioc容器;
return context;
} catch (Throwable ex) {
handleRunFailure(context, listeners, analyzers, ex);
throw new IllegalStateException(ex);
}
}
複製代碼
3. 生命週期流程:
// 使用SpringFactoriesLoader在應用的classpath中查找並加載全部可用的ApplicationContextInitializer。
// 使用SpringFactoriesLoader在應用的classpath中查找並加載全部可用的ApplicationListener。
初始化SpringApplication時候收集各類回調接口
// SpringFactoriesLoader能夠查找到並加載的SpringApplicationRunListener
SpringApplicationRunListeners listeners = this.getRunListeners(args);
// 說明SpringBoot開始執行了
listeners.starting();
// 建立而且配置SpringBoot使用環境
this.prepareEnvironment(listeners ); { listeners.environmentPrepared(); // 說明SpringBoot環境已經配置好 }
// 建立Spring容器
context = this.createApplicationContext()
// 配置Spring容器上下文
this.prepareContext(context, environment, listeners, applicationArguments, printedBanner); {
this.applyInitializers(context); { this.getInitializers() .initialize(context) }
listeners.contextPrepared(context); { this.listeners(). contextPrepared(context) // 在建立和準備好ApplicationContext以後,但在加載源以前調用。 }
listeners.contextLoaded(context); { this.listeners().contextLoaded(context) //在加載應用程序上下文後但刷新以前調用 }
}
// 刷新Spring容器,經過反射生成bean
this.refreshContext(context);
this.afterRefresh();
//上下文已刷新,應用程序已啓動,但還沒有調用commandlinerunner和applicationrunner
listeners.started(context);
// 查找當前ApplicationContext中是否註冊有CommandLineRunner,若是有,則遍歷執行它們。
this.callRunners(context, applicationArguments); { ApplicationRunner; CommandLineRunner; }
複製代碼
8、SpringBoot自動配置
SpringBoot爲咱們作的自動配置,確實方便快捷,可是對於新手來講,若是不大懂SpringBoot內部啓動原理,之後不免會吃虧。
入口類
咱們開發任何一個Spring Boot項目,都會用到以下的啓動類
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
複製代碼
從上面代碼能夠看出,Annotation定義(@SpringBootApplication)和類定義(SpringApplication.run)最爲耀眼,因此要揭開SpringBoot的神祕面紗,咱們要從這兩位開始就能夠了。
SpringBootApplication背後的祕密
@Target(ElementType.TYPE) // 註解的適用範圍,其中TYPE用於描述類、接口(包括包註解類型)或enum聲明
@Retention(RetentionPolicy.RUNTIME) // 註解的生命週期,保留到class文件中(三個生命週期)
@Documented // 代表這個註解應該被javadoc記錄
@Inherited // 子類能夠繼承該註解
@SpringBootConfiguration // 繼承了Configuration,表示當前是註解類
@EnableAutoConfiguration // 開啓springboot的註解功能,springboot的四大神器之一,其藉助@import的幫助
@ComponentScan(excludeFilters = { // 掃描路徑設置(具體使用待確認)
@Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {
...
}
複製代碼
雖然定義使用了多個Annotation進行了原信息標註,但實際上重要的只有三個Annotation:
因此,若是咱們使用以下的SpringBoot啓動類,整個SpringBoot應用依然能夠與以前的啓動類功能對等:
@Configuration
@EnableAutoConfiguration
@ComponentScan
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
複製代碼
每次寫這3個比較累,因此寫一個@SpringBootApplication方便點。接下來分別介紹這3個Annotation。
@Configuration
這裏的@Configuration對咱們來講不陌生,它就是JavaConfig形式的Spring Ioc容器的配置類使用的那個@Configuration,SpringBoot社區推薦使用基於JavaConfig的配置形式,因此,這裏的啓動類標註了@Configuration以後,自己其實也是一個IoC容器的配置類。
舉幾個簡單例子回顧下,XML跟config配置方式的區別:
表達形式層面 基於XML配置的方式是這樣:
而基於JavaConfig的配置方式是這樣:
@Configuration
public class MockConfiguration{
//bean定義
}
複製代碼
任何一個標註了@Configuration的Java類定義都是一個JavaConfig配置類。
註冊bean定義層面 基於XML的配置形式是這樣:
...而基於JavaConfig的配置形式是這樣的:
@Configuration
public class MockConfiguration{
@Bean
public MockService mockService(){
return new MockServiceImpl();
}
}
複製代碼
任何一個標註了@Bean的方法,其返回值將做爲一個bean定義註冊到Spring的IoC容器,方法名將默認成該bean定義的id。
表達依賴注入關係層面 爲了表達bean與bean之間的依賴關係,在XML形式中通常是這樣:
而基於JavaConfig的配置形式是這樣的:
@Configuration
public class MockConfiguration{
@Bean
public MockService mockService(){
return new MockServiceImpl(dependencyService());
}
@Bean
public DependencyService dependencyService(){
return new DependencyServiceImpl();
}java
}
複製代碼
若是一個bean的定義依賴其餘bean,則直接調用對應的JavaConfig類中依賴bean的建立方法就能夠了。
@ComponentScan
@ComponentScan這個註解在Spring中很重要,它對應XML配置中的元素,@ComponentScan的功能其實就是自動掃描並加載符合條件的組件(好比@Component和@Repository等)或者bean定義,最終將這些bean定義加載到IoC容器中。
咱們能夠經過basePackages等屬性來細粒度的定製@ComponentScan自動掃描的範圍,若是不指定,則默認Spring框架實現會從聲明@ComponentScan所在類的package進行掃描。
@EnableAutoConfiguration
我的感受@EnableAutoConfiguration這個Annotation最爲重要,因此放在最後來解讀,你們是否還記得Spring框架提供的各類名字爲@Enable開頭的Annotation定義?好比@EnableScheduling、@EnableCaching、@EnableMBeanExport等,@EnableAutoConfiguration的理念和作事方式其實一脈相承,簡單歸納一下就是,藉助@Import的支持,收集和註冊特定場景相關的bean定義。
而@EnableAutoConfiguration也是藉助@Import的幫助,將全部符合自動配置條件的bean定義加載到IoC容器,僅此而已!
@EnableAutoConfiguration做爲一個複合Annotation,其自身定義關鍵信息以下:
@SuppressWarnings("deprecation")
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import(EnableAutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {
...
}
複製代碼
兩個比較重要的註解:
AutoConfigurationPackage註解:
1 static class Registrar implements ImportBeanDefinitionRegistrar, DeterminableImports {
2
3 @Override
4 public void registerBeanDefinitions(AnnotationMetadata metadata,
5 BeanDefinitionRegistry registry) {
6 register(registry, new PackageImport(metadata).getPackageName());
7 }
複製代碼
它實際上是註冊了一個Bean的定義。
new PackageImport(metadata).getPackageName(),它其實返回了當前主程序類的 *同級以及子級 * 的包組件。
以上圖爲例,DemoApplication是和demo包同級,可是demo2這個類是DemoApplication的父級,和example包同級
也就是說,DemoApplication啓動加載的Bean中,並不會加載demo2,這也就是爲何,咱們要把DemoApplication放在項目的最高級中。
Import(AutoConfigurationImportSelector.class)註解:
能夠從圖中看出 ** AutoConfigurationImportSelector 繼承了 DeferredImportSelector 繼承了 ImportSelector**
ImportSelector有一個方法爲:selectImports。
@Override
public String[] selectImports(AnnotationMetadata annotationMetadata) {
if (!isEnabled(annotationMetadata)) {
return NO_IMPORTS;
}
AutoConfigurationMetadata autoConfigurationMetadata = AutoConfigurationMetadataLoader
.loadMetadata(this.beanClassLoader);
AnnotationAttributes attributes = getAttributes(annotationMetadata);
List<String> configurations = getCandidateConfigurations(annotationMetadata,
attributes);
configurations = removeDuplicates(configurations);
Set<String> exclusions = getExclusions(annotationMetadata, attributes);
checkExcludedClasses(configurations, exclusions);
configurations.removeAll(exclusions);
configurations = filter(configurations, autoConfigurationMetadata);
fireAutoConfigurationImportEvents(configurations, exclusions);
return StringUtils.toStringArray(configurations);
}
複製代碼
能夠看到第九行,它實際上是去加載 public static final String FACTORIES_RESOURCE_LOCATION = "META-INF/spring.factories";外部文件。這個外部文件,有不少自動配置的類。以下:
其中,最關鍵的要屬@Import(EnableAutoConfigurationImportSelector.class),藉助EnableAutoConfigurationImportSelector,@EnableAutoConfiguration能夠幫助SpringBoot應用將全部符合條件的@Configuration配置都加載到當前SpringBoot建立並使用的IoC容器。就像一隻「八爪魚」同樣。
自動配置幕後英雄:SpringFactoriesLoader詳解
藉助於Spring框架原有的一個工具類:SpringFactoriesLoader的支持,@EnableAutoConfiguration能夠智能的自動配置功效才得以大功告成!
SpringFactoriesLoader屬於Spring框架私有的一種擴展方案,其主要功能就是從指定的配置文件META-INF/spring.factories加載配置。
public abstract class SpringFactoriesLoader {
//...
public static <T> List<T> loadFactories(Class<T> factoryClass, ClassLoader classLoader) {
...
}
public static List<String> loadFactoryNames(Class<?> factoryClass, ClassLoader classLoader) {
....
}
}
複製代碼
配合@EnableAutoConfiguration使用的話,它更可能是提供一種配置查找的功能支持,即根據@EnableAutoConfiguration的完整類名org.springframework.boot.autoconfigure.EnableAutoConfiguration做爲查找的Key,獲取對應的一組@Configuration類
上圖就是從SpringBoot的autoconfigure依賴包中的META-INF/spring.factories配置文件中摘錄的一段內容,能夠很好地說明問題。
因此,@EnableAutoConfiguration自動配置的魔法騎士就變成了:從classpath中搜尋全部的META-INF/spring.factories配置文件,並將其中org.springframework.boot.autoconfigure.EnableutoConfiguration對應的配置項經過反射(Java Refletion)實例化爲對應的標註了@Configuration的JavaConfig形式的IoC容器配置類,而後彙總爲一個並加載到IoC容器。
SpringBoot的啓動原理基本算是講完了,爲了方便記憶,我根據上面的分析畫了張圖
深刻探索SpringApplication執行流程
SpringApplication的run方法的實現是咱們本次旅程的主要線路,該方法的主要流程大致能夠概括以下:
1) 若是咱們使用的是SpringApplication的靜態run方法,那麼,這個方法裏面首先要建立一個SpringApplication對象實例,而後調用這個建立好的SpringApplication的實例方法。在SpringApplication實例初始化的時候,它會提早作幾件事情:
public static ConfigurableApplicationContext run(Object[] sources, String[] args) {
return new SpringApplication(sources).run(args);
}
複製代碼
根據classpath裏面是否存在某個特徵類(org.springframework.web.context.ConfigurableWebApplicationContext)來決定是否應該建立一個爲Web應用使用的ApplicationContext類型。
使用SpringFactoriesLoader在應用的classpath中查找並加載全部可用的ApplicationContextInitializer。
使用SpringFactoriesLoader在應用的classpath中查找並加載全部可用的ApplicationListener。
推斷並設置main方法的定義類。
@SuppressWarnings({ "unchecked", "rawtypes" }) private void initialize(Object[] sources) { if (sources != null && sources.length > 0) { this.sources.addAll(Arrays.asList(sources)); } this.webEnvironment = deduceWebEnvironment(); setInitializers((Collection) getSpringFactoriesInstances( ApplicationContextInitializer.class)); setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class)); this.mainApplicationClass = deduceMainApplicationClass(); }
2) SpringApplication實例初始化完成而且完成設置後,就開始執行run方法的邏輯了,方法執行伊始,首先遍歷執行全部經過SpringFactoriesLoader能夠查找到並加載的SpringApplicationRunListener。調用它們的started()方法,告訴這些SpringApplicationRunListener,「嘿,SpringBoot應用要開始執行咯!」。
public ConfigurableApplicationContext run(String... args) {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
ConfigurableApplicationContext context = null;
FailureAnalyzers analyzers = null;
configureHeadlessProperty();
SpringApplicationRunListeners listeners = getRunListeners(args);
listeners.starting();
try {
ApplicationArguments applicationArguments = new DefaultApplicationArguments(
args);
ConfigurableEnvironment environment = prepareEnvironment(listeners,
applicationArguments);
Banner printedBanner = printBanner(environment);
context = createApplicationContext();
analyzers = new FailureAnalyzers(context);
prepareContext(context, environment, listeners, applicationArguments,
printedBanner);
       // 核心點:會打印springboot的啓動標誌,直到server.port端口啓動
refreshContext(context);
afterRefresh(context, applicationArguments);
listeners.finished(context, null);
stopWatch.stop();
if (this.logStartupInfo) {
new StartupInfoLogger(this.mainApplicationClass)
.logStarted(getApplicationLog(), stopWatch);
}
return context;
}
catch (Throwable ex) {
handleRunFailure(context, listeners, analyzers, ex);
throw new IllegalStateException(ex);
}
}
複製代碼
3) 建立並配置當前Spring Boot應用將要使用的Environment(包括配置要使用的PropertySource以及Profile)。
private ConfigurableEnvironment prepareEnvironment(
SpringApplicationRunListeners listeners,
ApplicationArguments applicationArguments) {
// Create and configure the environment
ConfigurableEnvironment environment = getOrCreateEnvironment();
configureEnvironment(environment, applicationArguments.getSourceArgs());
listeners.environmentPrepared(environment);
if (!this.webEnvironment) {
environment = new EnvironmentConverter(getClassLoader())
.convertToStandardEnvironmentIfNecessary(environment);
}
return environment;
}
複製代碼
4) 遍歷調用全部SpringApplicationRunListener的environmentPrepared()的方法,告訴他們:「當前SpringBoot應用使用的Environment準備好了咯!」。
public void environmentPrepared(ConfigurableEnvironment environment) {
for (SpringApplicationRunListener listener : this.listeners) {
listener.environmentPrepared(environment);
}
}
複製代碼
5) 若是SpringApplication的showBanner屬性被設置爲true,則打印banner。
private Banner printBanner(ConfigurableEnvironment environment) {
if (this.bannerMode == Banner.Mode.OFF) {
return null;
}
ResourceLoader resourceLoader = this.resourceLoader != null ? this.resourceLoader
: new DefaultResourceLoader(getClassLoader());
SpringApplicationBannerPrinter bannerPrinter = new SpringApplicationBannerPrinter(
resourceLoader, this.banner);
if (this.bannerMode == Mode.LOG) {
return bannerPrinter.print(environment, this.mainApplicationClass, logger);
}
return bannerPrinter.print(environment, this.mainApplicationClass, System.out);
}
複製代碼
6) 根據用戶是否明確設置了applicationContextClass類型以及初始化階段的推斷結果,決定該爲當前SpringBoot應用建立什麼類型的ApplicationContext並建立完成,而後根據條件決定是否添加ShutdownHook,決定是否使用自定義的BeanNameGenerator,決定是否使用自定義的ResourceLoader,固然,最重要的,將以前準備好的Environment設置給建立好的ApplicationContext使用。
7) ApplicationContext建立好以後,SpringApplication會再次藉助Spring-FactoriesLoader,查找並加載classpath中全部可用的ApplicationContext-Initializer,而後遍歷調用這些ApplicationContextInitializer的initialize(applicationContext)方法來對已經建立好的ApplicationContext進行進一步的處理。
@SuppressWarnings({ "rawtypes", "unchecked" })
protected void applyInitializers(ConfigurableApplicationContext context) {
for (ApplicationContextInitializer initializer : getInitializers()) {
Class<?> requiredType = GenericTypeResolver.resolveTypeArgument(
initializer.getClass(), ApplicationContextInitializer.class);
Assert.isInstanceOf(requiredType, context, "Unable to call initializer.");
initializer.initialize(context);
}
}
複製代碼
8) 遍歷調用全部SpringApplicationRunListener的contextPrepared()方法。
private void prepareContext(ConfigurableApplicationContext context,
ConfigurableEnvironment environment, SpringApplicationRunListeners listeners,
ApplicationArguments applicationArguments, Banner printedBanner) {
context.setEnvironment(environment);
postProcessApplicationContext(context);
applyInitializers(context);
listeners.contextPrepared(context);
if (this.logStartupInfo) {
logStartupInfo(context.getParent() == null);
logStartupProfileInfo(context);
}
// Add boot specific singleton beans
context.getBeanFactory().registerSingleton("springApplicationArguments",
applicationArguments);
if (printedBanner != null) {
context.getBeanFactory().registerSingleton("springBootBanner", printedBanner);
}
// Load the sources
Set<Object> sources = getSources();
Assert.notEmpty(sources, "Sources must not be empty");
load(context, sources.toArray(new Object[sources.size()]));
listeners.contextLoaded(context);
}
複製代碼
9) 最核心的一步,將以前經過@EnableAutoConfiguration獲取的全部配置以及其餘形式的IoC容器配置加載到已經準備完畢的ApplicationContext。
private void prepareAnalyzer(ConfigurableApplicationContext context,
FailureAnalyzer analyzer) {
if (analyzer instanceof BeanFactoryAware) {
((BeanFactoryAware) analyzer).setBeanFactory(context.getBeanFactory());
}
}
複製代碼
10) 遍歷調用全部SpringApplicationRunListener的contextLoaded()方法。
public void contextLoaded(ConfigurableApplicationContext context) {
for (SpringApplicationRunListener listener : this.listeners) {
listener.contextLoaded(context);
}
}
複製代碼
11) 調用ApplicationContext的refresh()方法,完成IoC容器可用的最後一道工序。
private void refreshContext(ConfigurableApplicationContext context) {
refresh(context);
if (this.registerShutdownHook) {
try {
context.registerShutdownHook();
}
catch (AccessControlException ex) {
// Not allowed in some environments.
}
}
}
複製代碼
12) 查找當前ApplicationContext中是否註冊有CommandLineRunner,若是有,則遍歷執行它們。
private void callRunners(ApplicationContext context, ApplicationArguments args) {
List<Object> runners = new ArrayList<Object>();
runners.addAll(context.getBeansOfType(ApplicationRunner.class).values());
runners.addAll(context.getBeansOfType(CommandLineRunner.class).values());
AnnotationAwareOrderComparator.sort(runners);
for (Object runner : new LinkedHashSet<Object>(runners)) {
if (runner instanceof ApplicationRunner) {
callRunner((ApplicationRunner) runner, args);
}
if (runner instanceof CommandLineRunner) {
callRunner((CommandLineRunner) runner, args);
}
}
}
複製代碼
13) 正常狀況下,遍歷執行SpringApplicationRunListener的finished()方法、(若是整個過程出現異常,則依然調用全部SpringApplicationRunListener的finished()方法,只不過這種狀況下會將異常信息一併傳入處理)
去除事件通知點後,整個流程以下:
public void finished(ConfigurableApplicationContext context, Throwable exception) {
for (SpringApplicationRunListener listener : this.listeners) {
callFinishedListener(listener, context, exception);
}
}
複製代碼
自定義事件監聽機制
SpringApplicationRunListener 接口規定了 SpringBoot 的生命週期,在各個生命週期廣播相應的事件,調用實際的 ApplicationListener 類。經過對 SpringApplicationRunListener 的分析,也能夠對 SpringBoot 的整個啓動過程的理解會有很大幫助。
public interface SpringApplicationRunListener {
//當run方法首次啓動時當即調用。可用於很是早期的初始化。
void starting();
//在準備好環境後,但在建立ApplicationContext以前調用。
void environmentPrepared(ConfigurableEnvironment environment);
//在建立和準備好ApplicationContext以後,但在加載源以前調用。
void contextPrepared(ConfigurableApplicationContext context);
//在加載應用程序上下文後但刷新以前調用
void contextLoaded(ConfigurableApplicationContext context);
//上下文已刷新,應用程序已啓動,但還沒有調用commandlinerunner和applicationrunner。
void started(ConfigurableApplicationContext context);
//在運行方法完成以前當即調用,此時應用程序上下文已刷新,
//而且全部commandlinerunner和applicationrunner都已調用。
//2.0 纔有
void running(ConfigurableApplicationContext context);
//在運行應用程序時發生故障時調用。2.0 纔有
void failed(ConfigurableApplicationContext context, Throwable exception);
}
ApplicationStartingEvent在運行開始時但在任何處理以前發送,偵聽器和初始值設定項的註冊除外。
ApplicationEnvironmentPreparedEvent在上下文中要使用的環境已知但在建立上下文以前發送。
ApplicationPreparedEvent將在刷新開始以前,但在加載bean定義以後發送。
ApplicationStartedEvent在刷新上下文以後,但在調用任何應用程序和命令行運行程序以前發送。
ApplicationreadyEvent在調用任何應用程序和命令行運行程序以後,將發送。它表示應用程序已準備好服務請求。
ApplicationFailedEvent若是啓動時出現異常,則發送。
複製代碼
ApplicationContextInitializer
package web.listeners;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
/**
* @author dongmei.tan
* @date 2019/5/26 17:09
*/
public class HelloApplicationContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
@Override
public void initialize(ConfigurableApplicationContext configurableApplicationContext) {
System.out.println("HelloApplicationContextInitializer...initialize...");
}
}
複製代碼
SpringApplicationRunListener
package web.listeners;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.SpringApplicationRunListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;
/**
* @author dongmei.tan
* @date 2019/5/26 17:16
*/
public class HelloSpringApplicationRunListener implements SpringApplicationRunListener {
public HelloSpringApplicationRunListener(SpringApplication application, String[] args) {
}
@Override
public void starting() {
System.out.println("SpringApplicationRunListener...starting.. ");
}
@Override
public void environmentPrepared(ConfigurableEnvironment environment) {
System.out.println("SpringApplicationRunListener...environmentPrepared..; ==environment" + environment);
}
@Override
public void contextPrepared(ConfigurableApplicationContext context) {
System.out.println("SpringApplicationRunListener...contextPrepared..==> " + context);
}
@Override
public void contextLoaded(ConfigurableApplicationContext context) {
System.out.println("SpringApplicationRunListener...starting..==> " + context);
}
@Override
public void started(ConfigurableApplicationContext context) {
System.out.println("SpringApplicationRunListener...started..==> " + context);
}
@Override
public void running(ConfigurableApplicationContext context) {
System.out.println("SpringApplicationRunListener...running..==> " + context);
}
@Override
public void failed(ConfigurableApplicationContext context, Throwable exception) {
System.out.println("SpringApplicationRunListener...failed..==> " + context);
}
}
複製代碼
配置(META-INF/spring.factories)
org.springframework.context.ApplicationContextInitializer=\
web.listeners.HelloApplicationContextInitializer
# Application Listeners
org.springframework.boot.SpringApplicationRunListener=\
web.listeners.HelloSpringApplicationRunListener
複製代碼
只須要放在ioc容器中
ApplicationRunner
CommandLineRunner
若是在SpringApplication啓動後須要運行一些特定的代碼,能夠實現ApplicationRunner或CommandLineRunner接口。兩個接口以相同的方式工做,並提供一個單獨的運行方法,該方法在SpringApplication.Run(…)完成以前調用。
commandLineRunner接口以簡單的字符串數組形式提供對應用程序參數的訪問,而applicationRunner使用前面討論過的applicationArguments接口。下面的示例顯示了帶有run方法的commandlinerunner:
package web.listeners;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
/**
* @author dongmei.tan
* @date 2019/5/26 17:21
*/
@Component
public class HelloApplicationRunner implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("ApplicationRunner...run..");
}
}
package web.listeners;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
/**
* @author dongmei.tan
* @date 2019/5/26 17:22
*/
@Component
public class HelloCommandLineRunner implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("CommandLineRunner...run...");
}
}
複製代碼