小夥伴們是否想起曾經被 SSM 整合支配的恐懼?相信不少小夥伴都是有過這樣的經歷的,一大堆配置問題,各類排除掃描,導入一個新的依賴又得添加新的配置。自從有了 SpringBoot 以後,咋們就起飛了!各類零配置開箱即用,而咱們之因此開發起來可以這麼爽,自動配置的功勞少不了,今天咱們就一塊兒來討論一下 SpringBoot 自動配置原理。html
本文主要分爲三大部分:java
SpringBoot 源碼經常使用註解拾遺web
SpringBoot 啓動過程spring
SpringBoot 自動配置原理數組
這部分主要講一下 SpringBoot 源碼中常用到的註解,以掃清後面閱讀源碼時候的障礙。app
當可能大量同時使用到幾個註解到同一個類上,就能夠考慮將這幾個註解到別的註解上。被註解的註解咱們就稱之爲組合註解。less
元註解:能夠註解到別的註解上的註解。ide
組合註解:被註解的註解咱們就稱之爲組合註解。spring-boot
@Value
就至關於傳統 xml 配置文件中的 value 字段。源碼分析
假設存在代碼:
@Component
public class Person {
@Value("i am name")
private String name;
}
複製代碼
上面代碼等價於的配置文件:
<bean class="Person">
<property name ="name" value="i am name"></property>
</bean>
複製代碼
咱們知道配置文件中的 value 的取值能夠是:
字面量
經過 ${key}
方式從環境變量中獲取值
經過 ${key}
方式全局配置文件中獲取值
#{SpEL}
因此,咱們就能夠經過
@Value(${key})
的方式獲取全局配置文件中的指定配置項。
若是咱們須要取 N 個配置項,經過 @Value 的方式去配置項須要一個一個去取,這就顯得有點 low 了。咱們可使用 @ConfigurationProperties
。
標有
@ConfigurationProperties
的類的全部屬性和配置文件中相關的配置項進行綁定。(默認從全局配置文件中獲取配置值),綁定以後咱們就能夠經過這個類去訪問全局配置文件中的屬性值了。
下面看一個實例:
person.name=kundy
person.age=13
person.sex=male
複製代碼
@Component
@ConfigurationProperties(prefix = "person")
public class Person {
private String name;
private Integer age;
private String sex;
}
複製代碼
這裏 @ConfigurationProperties 有一個
prefix
參數,主要是用來指定該配置項在配置文件中的前綴。
@Import
註解支持導入普通 java 類,並將其聲明成一個bean。主要用於將多個分散的 java config 配置類融合成一個更大的 config 類。
@Import
註解在 4.2 以前只支持導入配置類。
在4.2以後 @Import
註解支持導入普通的 java 類,並將其聲明成一個 bean。
**@Import 三種使用方式 **
直接導入普通的 Java 類。
配合自定義的 ImportSelector 使用。
配合 ImportBeanDefinitionRegistrar 使用。
public class Circle {
public void sayHi() {
System.out.println("Circle sayHi()");
}
}
複製代碼
@Import({Circle.class})
@Configuration
public class MainConfig {
}
複製代碼
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(MainConfig.class);
Circle circle = context.getBean(Circle.class);
circle.sayHi();
}
複製代碼
Circle sayHi()
能夠看到咱們順利的從 IOC 容器中獲取到了 Circle 對象,證實咱們在配置類中導入的 Circle 類,確實被聲明爲了一個 Bean。
ImportSelector
是一個接口,該接口中只有一個 selectImports 方法,用於返回全類名數組。因此利用該特性咱們能夠給容器動態導入 N 個 Bean。
public class Triangle {
public void sayHi(){
System.out.println("Triangle sayHi()");
}
}
複製代碼
public class MyImportSelector implements ImportSelector {
@Override
public String[] selectImports(AnnotationMetadata annotationMetadata) {
return new String[]{"annotation.importannotation.waytwo.Triangle"};
}
}
複製代碼
@Import({Circle.class,MyImportSelector.class})
@Configuration
public class MainConfigTwo {
}
複製代碼
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(MainConfigTwo.class);
Circle circle = context.getBean(Circle.class);
Triangle triangle = context.getBean(Triangle.class);
circle.sayHi();
triangle.sayHi();
}
複製代碼
Circle sayHi()
Triangle sayHi()
能夠看到 Triangle 對象也被 IOC 容器成功的實例化出來了。
ImportBeanDefinitionRegistrar
也是一個接口,它能夠手動註冊bean到容器中,從而咱們能夠對類進行個性化的定製。(須要搭配 @Import 與 @Configuration 一塊兒使用。)
public class Rectangle {
public void sayHi() {
System.out.println("Rectangle sayHi()");
}
}
複製代碼
public class MyImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {
@Override
public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry beanDefinitionRegistry) {
RootBeanDefinition rootBeanDefinition = new RootBeanDefinition(Rectangle.class);
// 註冊一個名字叫作 rectangle 的 bean
beanDefinitionRegistry.registerBeanDefinition("rectangle", rootBeanDefinition);
}
}
複製代碼
@Import({Circle.class, MyImportSelector.class, MyImportBeanDefinitionRegistrar.class})
@Configuration
public class MainConfigThree {
}
複製代碼
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(MainConfigThree.class);
Circle circle = context.getBean(Circle.class);
Triangle triangle = context.getBean(Triangle.class);
Rectangle rectangle = context.getBean(Rectangle.class);
circle.sayHi();
triangle.sayHi();
rectangle.sayHi();
}
複製代碼
Circle sayHi()
Triangle sayHi()
Rectangle sayHi()
嗯對,Rectangle 對象也被註冊進來了。
> @Conditional
註釋能夠實現只有在特定條件知足時才啓用一些配置。
下面看一個簡單的例子:
public class ConditionBean {
public void sayHi() {
System.out.println("ConditionBean sayHi()");
}
}
複製代碼
public class MyCondition implements Condition {
@Override
public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
return true;
}
}
複製代碼
@Configuration
@Conditional(MyCondition.class)
public class ConditionConfig {
@Bean
public ConditionBean conditionBean(){
return new ConditionBean();
}
}
複製代碼
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(ConditionConfig.class);
ConditionBean conditionBean = context.getBean(ConditionBean.class);
conditionBean.sayHi();
}
複製代碼
由於 Condition 的 matches 方法直接返回了 true,配置類會生效,咱們能夠把 matches 改爲返回 false,則配置類就不會生效了。
除了自定義 Condition,Spring 還爲咱們擴展了一些經常使用的 Condition。
擴展註解 | 做用 |
---|---|
ConditionalOnBean | 容器中存在指定 Bean,則生效。 |
ConditionalOnMissingBean | 容器中不存在指定 Bean,則生效。 |
ConditionalOnClass | 系統中有指定的類,則生效。 |
ConditionalOnMissingClass | 系統中沒有指定的類,則生效。 |
ConditionalOnProperty | 系統中指定的屬性是否有指定的值。 |
ConditionalOnWebApplication | 當前是web環境,則生效。 |
在看源碼的過程當中,咱們會看到如下四個類的方法常常會被調用,咱們須要對一下幾個類有點印象:
ApplicationContextInitializer
ApplicationRunner
CommandLineRunner
SpringApplicationRunListener
下面開始源碼分析,先從 SpringBoot 的啓動類的 run() 方法開始看,如下是調用鏈:SpringApplication.run()
-> run(new Class[]{primarySource}, args)
-> new SpringApplication(primarySources)).run(args)
。
一直在run,終於到重點了,咱們直接看 new SpringApplication(primarySources)).run(args)
這個方法。
上面的方法主要包括兩大步驟:
建立 SpringApplication 對象。
運行 run() 方法。
public SpringApplication(ResourceLoader resourceLoader, Class... primarySources) {
this.sources = new LinkedHashSet();
this.bannerMode = Mode.CONSOLE;
this.logStartupInfo = true;
this.addCommandLineProperties = true;
this.addConversionService = true;
this.headless = true;
this.registerShutdownHook = true;
this.additionalProfiles = new HashSet();
this.isCustomEnvironment = false;
this.resourceLoader = resourceLoader;
Assert.notNull(primarySources, "PrimarySources must not be null");
// 保存主配置類(這裏是一個數組,說明能夠有多個主配置類)
this.primarySources = new LinkedHashSet(Arrays.asList(primarySources));
// 判斷當前是不是一個 Web 應用
this.webApplicationType = WebApplicationType.deduceFromClasspath();
// 從類路徑下找到 META/INF/Spring.factories 配置的全部 ApplicationContextInitializer,而後保存起來
this.setInitializers(this.getSpringFactoriesInstances(ApplicationContextInitializer.class));
// 從類路徑下找到 META/INF/Spring.factories 配置的全部 ApplicationListener,而後保存起來
this.setListeners(this.getSpringFactoriesInstances(ApplicationListener.class));
// 從多個配置類中找到有 main 方法的主配置類(只有一個)
this.mainApplicationClass = this.deduceMainApplicationClass();
}
複製代碼
public ConfigurableApplicationContext run(String... args) {
// 建立計時器
StopWatch stopWatch = new StopWatch();
stopWatch.start();
// 聲明 IOC 容器
ConfigurableApplicationContext context = null;
Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList();
this.configureHeadlessProperty();
// 從類路徑下找到 META/INF/Spring.factories 獲取 SpringApplicationRunListeners
SpringApplicationRunListeners listeners = this.getRunListeners(args);
// 回調全部 SpringApplicationRunListeners 的 starting() 方法
listeners.starting();
Collection exceptionReporters;
try {
// 封裝命令行參數
ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
// 準備環境,包括建立環境,建立環境完成後回調 SpringApplicationRunListeners#environmentPrepared()方法,表示環境準備完成
ConfigurableEnvironment environment = this.prepareEnvironment(listeners, applicationArguments);
this.configureIgnoreBeanInfo(environment);
// 打印 Banner
Banner printedBanner = this.printBanner(environment);
// 建立 IOC 容器(決定建立 web 的 IOC 容器仍是普通的 IOC 容器)
context = this.createApplicationContext();
exceptionReporters = this.getSpringFactoriesInstances(SpringBootExceptionReporter.class, new Class[]{ConfigurableApplicationContext.class}, context);
/* * 準備上下文環境,將 environment 保存到 IOC 容器中,而且調用 applyInitializers() 方法 * applyInitializers() 方法回調以前保存的全部的 ApplicationContextInitializer 的 initialize() 方法 * 而後回調全部的 SpringApplicationRunListener#contextPrepared() 方法 * 最後回調全部的 SpringApplicationRunListener#contextLoaded() 方法 */
this.prepareContext(context, environment, listeners, applicationArguments, printedBanner);
// 刷新容器,IOC 容器初始化(若是是 Web 應用還會建立嵌入式的 Tomcat),掃描、建立、加載全部組件的地方
this.refreshContext(context);
// 從 IOC 容器中獲取全部的 ApplicationRunner 和 CommandLineRunner 進行回調
this.afterRefresh(context, applicationArguments);
stopWatch.stop();
if (this.logStartupInfo) {
(new StartupInfoLogger(this.mainApplicationClass)).logStarted(this.getApplicationLog(), stopWatch);
}
// 調用 全部 SpringApplicationRunListeners#started()方法
listeners.started(context);
this.callRunners(context, applicationArguments);
} catch (Throwable var10) {
this.handleRunFailure(context, var10, exceptionReporters, listeners);
throw new IllegalStateException(var10);
}
try {
listeners.running(context);
return context;
} catch (Throwable var9) {
this.handleRunFailure(context, var9, exceptionReporters, (SpringApplicationRunListeners)null);
throw new IllegalStateException(var9);
}
}
複製代碼
小結:
run() 階段主要就是回調本節開頭提到過的4個監聽器中的方法與加載項目中組件到 IOC 容器中,而全部須要回調的監聽器都是從類路徑下的
META/INF/Spring.factories
中獲取,從而達到啓動先後的各類定製操做。
SpringBoot 項目的一切都要從
@SpringBootApplication
這個註解開始提及。
@SpringBootApplication 標註在某個類上說明:
這個類是 SpringBoot 的主配置類。
SpringBoot 就應該運行這個類的 main 方法來啓動 SpringBoot 應用。
該註解的定義以下:
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(
excludeFilters = {@Filter(
type = FilterType.CUSTOM,
classes = {TypeExcludeFilter.class}
), @Filter(
type = FilterType.CUSTOM,
classes = {AutoConfigurationExcludeFilter.class}
)}
)
public @interface SpringBootApplication {
複製代碼
能夠看到 SpringBootApplication
註解是一個組合註解(關於組合註解文章的開頭有講到),其主要組合了一下三個註解:
@SpringBootConfiguration
:該註解表示這是一個 SpringBoot 的配置類,其實它就是一個 @Configuration 註解而已。
@ComponentScan
:開啓組件掃描。
@EnableAutoConfiguration
:從名字就能夠看出來,就是這個類開啓自動配置的。嗯,自動配置的奧祕全都在這個註解裏面。
先看該註解是怎麼定義的:
@AutoConfigurationPackage
@Import({AutoConfigurationImportSelector.class})
public @interface EnableAutoConfiguration {
複製代碼
從字面意思理解就是自動配置包。點進去能夠看到就是一個 @Import 註解:
@Import({Registrar.class})
,導入了一個 Registrar 的組件。關於 @Import 的用法文章上面也有介紹哦。
咱們在 Registrar 類中的 registerBeanDefinitions 方法上打上斷點,能夠看到返回了一個包名,該包名其實就是主配置類所在的包。
一句話:@AutoConfigurationPackage 註解就是將主配置類(@SpringBootConfiguration標註的類)的所在包及下面全部子包裏面的全部組件掃描到Spring容器中。因此說,默認狀況下主配置類包及子包之外的組件,Spring 容器是掃描不到的。
該註解給當前配置類導入另外的 N 個自動配置類。(該註解詳細用法上文有說起)。
那具體的導入規則是什麼呢?咱們來看一下源碼。在開始看源碼以前,先囉嗦兩句。就像小馬哥說的,咱們看源碼不用所有都看,不用每一行代碼都弄明白是什麼意思,咱們只要抓住關鍵的地方就能夠了。
咱們知道 AutoConfigurationImportSelector 的 selectImports 就是用來返回須要導入的組件的全類名數組的,那麼如何獲得這些數組呢?
在 selectImports 方法中調用了一個 getAutoConfigurationEntry() 方法。
因爲篇幅問題我就不一一截圖了,我直接告訴大家調用鏈:在 getAutoConfigurationEntry() -> getCandidateConfigurations() -> loadFactoryNames()。
在這裏 loadFactoryNames() 方法傳入了 EnableAutoConfiguration.class 這個參數。先記住這個參數,等下會用到。
loadFactoryNames() 中關鍵的三步:
從當前項目的類路徑中獲取全部 META-INF/spring.factories
這個文件下的信息。
將上面獲取到的信息封裝成一個 Map 返回。
從返回的 Map 中經過剛纔傳入的 EnableAutoConfiguration.class
參數,獲取該 key 下的全部值。
聽我這樣說完可能會有點懵,咱們來看一下 META-INF/spring.factories
這類文件是什麼就不懵了。固然在不少第三方依賴中都會有這個文件,通常每導入一個第三方的依賴,除了自己的jar包之外,還會有一個 xxx-spring-boot-autoConfigure
,這個就是第三方依賴本身編寫的自動配置類。咱們如今就以 spring-boot-autocongigure 這個依賴來講。
能夠看到 EnableAutoConfiguration 下面有不少類,這些就是咱們項目進行自動配置的類。
一句話:將類路徑下 META-INF/spring.factories
裏面配置的全部 EnableAutoConfiguration 的值加入到 Spring 容器中。
經過上面方式,全部的自動配置類就被導進主配置類中了。可是這麼多的配置類,明顯有不少自動配置咱們日常是沒有使用到的,沒理由所有都生效吧。
接下來咱們以 HttpEncodingAutoConfiguration
爲例來看一個自動配置類是怎麼工做的。爲啥選這個類呢?主要是這個類比較的簡單典型。
先看一下該類標有的註解:
@Configuration
@EnableConfigurationProperties({HttpProperties.class})
@ConditionalOnWebApplication(
type = Type.SERVLET
)
@ConditionalOnClass({CharacterEncodingFilter.class})
@ConditionalOnProperty(
prefix = "spring.http.encoding",
value = {"enabled"},
matchIfMissing = true
)
public class HttpEncodingAutoConfiguration {
複製代碼
@Configuration:標記爲配置類。
@ConditionalOnWebApplication:web應用下才生效。
@ConditionalOnClass:指定的類(依賴)存在才生效。
@ConditionalOnProperty:主配置文件中存在指定的屬性才生效。
@EnableConfigurationProperties({HttpProperties.class}):啓動指定類的ConfigurationProperties功能;將配置文件中對應的值和 HttpProperties 綁定起來;並把 HttpProperties 加入到 IOC 容器中。
由於 @EnableConfigurationProperties({HttpProperties.class}) 把配置文件中的配置項與當前 HttpProperties 類綁定上了。而後在 HttpEncodingAutoConfiguration 中又引用了 HttpProperties ,因此最後就能在 HttpEncodingAutoConfiguration 中使用配置文件中的值了。最終經過 @Bean 和一些條件判斷往容器中添加組件,實現自動配置。(固然該Bean中屬性值是從 HttpProperties 中獲取)
HttpProperties 經過 @ConfigurationProperties 註解將配置文件與自身屬性綁定。
全部在配置文件中能配置的屬性都是在 xxxProperties 類中封裝着;配置文件能配置什麼就能夠參照某個功能對應的這個屬性類。
@ConfigurationProperties(
prefix = "spring.http"
)// 從配置文件中獲取指定的值和bean的屬性進行綁定
public class HttpProperties {
複製代碼
小結:
SpringBoot啓動會加載大量的自動配置類。
咱們看須要的功能有沒有SpringBoot默認寫好的自動配置類。
咱們再來看這個自動配置類中到底配置了那些組件(只要咱們要用的組件有,咱們就不須要再來配置了)。
給容器中自動配置類添加組件的時候,會從properties類中獲取某些屬性。咱們就能夠在配置文件中指定這些屬性的值。
xxxAutoConfiguration
:自動配置類給容器中添加組件。
xxxProperties
:封裝配置文件中相關屬性。
不知道小夥伴們有沒有發現,不少須要待加載的類都放在類路徑下的META-INF/Spring.factories
文件下,而不是直接寫死這代碼中,這樣作就能夠很方便咱們本身或者是第三方去擴展,咱們也能夠實現本身 starter
,讓SpringBoot 去加載。如今明白爲何 SpringBoot 能夠實現零配置,開箱即用了吧!
文章有點長,感謝你們的閱讀!以爲不錯能夠點個贊哦!
參考文章:
- www.cnblogs.com/duanxz/p/37…