- 資訊首頁(yè) > 開(kāi)發(fā)技術(shù) >
- SpringBoot自動(dòng)配置原理,你真的懂嗎?(簡(jiǎn)單易懂)
上面博文()我們簡(jiǎn)單的介紹了什么是SpringBoot,以及如何使用SpringBoot,但是我們對于SpringBoot的基本原理并沒(méi)有介紹,這篇博文我們重點(diǎn)介紹SpringBoot是如何實(shí)現的自動(dòng)配置。
在我們的pom文件中最核心的依賴(lài)就一個(gè):
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.4.4</version> <relativePath/> </parent>
它的父項目依賴(lài),規定所有依賴(lài)的版本信息:
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-dependencies</artifactId> <version>2.4.4</version> </parent>
由此,我們發(fā)現springboot框架幾乎聲明了所有開(kāi)發(fā)中常用的依賴(lài)的版本號,無(wú)需關(guān)注版本號,而且實(shí)現了自動(dòng)版本仲裁機制,當然了我們也可以根據我們的需要,替換掉默認的依賴(lài)版本。
@SpringBootApplication public class BootApplication { public static void main(String[] args) { SpringApplication.run(BootApplication.class, args); } }
在上面的啟動(dòng)類(lèi)中我們發(fā)現了一個(gè)陌生的注解@SpringBootApplication,這個(gè)注解的是什么含義呢?我們點(diǎn)進(jìn)去看一下。
@SpringBootConfiguration @EnableAutoConfiguration @ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class), @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
其實(shí)@SpringBootApplication是上面三個(gè)注解的組合體,我們對這三個(gè)注解理解清楚就可以了,下面逐個(gè)進(jìn)行解釋?zhuān)?/p>
@Configuration public @interface SpringBootConfiguration {
@Configuration我們并不陌生,它允許在上下文中注冊額外的bean或導入其他配置類(lèi),@SpringBootConfiguration其實(shí)代表當前類(lèi)是一個(gè)配置類(lèi)。
EnableAutoConfiguration的目的是啟動(dòng)SpringBoot的自動(dòng)配置機制。
@AutoConfigurationPackage @Import(AutoConfigurationImportSelector.class) public @interface EnableAutoConfiguration {
@Import(AutoConfigurationPackages.Registrar.class) public @interface AutoConfigurationPackage {
AutoConfigurationPackage注解的作用是將 添加該注解的類(lèi)所在的package 作為 自動(dòng)配置package 進(jìn)行管理。也就是說(shuō)當SpringBoot應用啟動(dòng)時(shí)默認會(huì )將啟動(dòng)類(lèi)所在的package作為自動(dòng)配置的package。然后使用@Import注解將其注入到ioc容器中。這樣,可以在容器中拿到該路徑。
static class Registrar implements ImportBeanDefinitionRegistrar, DeterminableImports { @Override public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) { register(registry, new PackageImports(metadata).getPackageNames().toArray(new String[0])); } @Override public Set<Object> determineImports(AnnotationMetadata metadata) { return Collections.singleton(new PackageImports(metadata)); } }
重點(diǎn)看下registerBeanDefinitions方法。
方法的第二個(gè)參數通過(guò)new PackageImport(metadata).getPackageName()
方法設置。
接著(zhù)看下PackageImport的構造器方法。
PackageImports(AnnotationMetadata metadata) { AnnotationAttributes attributes = AnnotationAttributes .fromMap(metadata.getAnnotationAttributes(AutoConfigurationPackage.class.getName(), false)); List<String> packageNames = new ArrayList<>(Arrays.asList(attributes.getStringArray("basePackages"))); for (Class<?> basePackageClass : attributes.getClassArray("basePackageClasses")) { packageNames.add(basePackageClass.getPackage().getName()); } if (packageNames.isEmpty()) { packageNames.add(ClassUtils.getPackageName(metadata.getClassName())); } this.packageNames = Collections.unmodifiableList(packageNames); }
ClassUtils.getPackageName(metadata.getClassName())獲取標注@AutoConfigurationPackage注解的類(lèi)的全限定名。
最后,利用Registrar給容器中導入一系列組件,將指定的包下的所有組件導入進(jìn)來(lái)。
使用Import自動(dòng)導入所有符合自動(dòng)配置條件的Bean定義并加載到IOC容器
@Override public void process(AnnotationMetadata annotationMetadata, DeferredImportSelector deferredImportSelector) { Assert.state(deferredImportSelector instanceof AutoConfigurationImportSelector, () -> String.format("Only %s implementations are supported, got %s", AutoConfigurationImportSelector.class.getSimpleName(), deferredImportSelector.getClass().getName())); AutoConfigurationEntry autoConfigurationEntry = ((AutoConfigurationImportSelector) deferredImportSelector) .getAutoConfigurationEntry(annotationMetadata); this.autoConfigurationEntries.add(autoConfigurationEntry); for (String importClassName : autoConfigurationEntry.getConfigurations()) { this.entries.putIfAbsent(importClassName, annotationMetadata); } }
1、利用getAutoConfigurationEntry(annotationMetadata);給容器中批量導入一些組件
2、調用List configurations = getCandidateConfigurations(annotationMetadata, attributes)獲取到所有需要導入到容器中的配置類(lèi)
3、利用工廠(chǎng)加載 Map<String, List> loadSpringFactories(@Nullable ClassLoader classLoader);得到所有的組件
4、從META-INF/spring.factories位置來(lái)加載一個(gè)文件。
默認掃描我們當前系統里面所有META-INF/spring.factories位置的文件
spring-boot-autoconfigure-2.4.4.RELEASE.jar包里面也有META-INF/spring.factories
文件里面寫(xiě)死了spring-boot一啟動(dòng)就要給容器中加載的所有配置類(lèi)spring-boot-autoconfigure-2.4.4.RELEASE.jar/META-INF/spring.factories,一共130個(gè)自動(dòng)配置類(lèi)。
130個(gè)場(chǎng)景的所有自動(dòng)配置,會(huì )在springboot啟動(dòng)的時(shí)候默認全部加載。xxxxAutoConfiguration會(huì )按照條件裝配規則(@Conditional),最終會(huì )按需配置。
SpringBoot為我們的應用程序啟用了三個(gè)功能:自動(dòng)配置,組件掃描,以及能夠在"應用類(lèi)"上定義額外的配置。
@Component
在應用程序所在的軟件包上啟用掃描,指定掃描哪些Spring注解。
ServletWebServerFactoryAutoConfiguration為例
在130個(gè)場(chǎng)景有我們比較熟悉兩個(gè)組件,ServletWebServerFactoryAutoConfiguration和WebMvcAutoConfiguration,我們以ServletWebServerFactoryAutoConfiguration為例,看一下SpringBoot是如何自動(dòng)裝配的webServer。
在注解中我們看到了大量以@Conditional開(kāi)頭的注解,即條件裝配,滿(mǎn)足Conditional指定的條件,則進(jìn)行組件注入。@EnableConfigurationProperties(ServerProperties.class)+@ConfigurationProperties(prefix = “server”, ignoreUnknownFields = true),讀取我們在配置文件編寫(xiě)的屬性,并把它封裝到JavaBean中,以供隨時(shí)使用。
此時(shí)我們的Tomcat容器已經(jīng)以Bean的形式被注入到了IOC容器中。
如果發(fā)現應用中不需要特定自動(dòng)配置類(lèi),則可以使用exclude屬性@SpringBootApplication
來(lái)禁用它們,如以下示例所示:
import org.springframework.boot.autoconfigure.*; import org.springframework.boot.autoconfigure.jdbc.*; @SpringBootApplication(exclude={DataSourceAutoConfiguration.class}) //@SpringBootApplication(excludeName = {"org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration"}) public class MyApplication { }
如果該類(lèi)不在類(lèi)路徑中,則可以使用excludeName
注釋的屬性,并指定完全限定的名稱(chēng)(全類(lèi)名字符串)。定義排除項,即可以是用哪個(gè)注釋級別也可以使用屬性來(lái)定義。
用戶(hù)直接自己@Bean替換底層的組件
用戶(hù)根據這個(gè)組件是獲取的配置文件的什么值,可以自行修改。
EnableAutoConfiguration —> 掃描xxxxxAutoConfiguration —> 根據條件@Conditional裝配組件 —>根據xxxxProperties加載屬性值 ----> application.properties
到此這篇關(guān)于SpringBoot自動(dòng)配置原理,你真的懂嗎?的文章就介紹到這了,更多相關(guān)SpringBoot自動(dòng)配置原理內容請搜索腳本之家以前的文章或繼續瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng )、來(lái)自互聯(lián)網(wǎng)轉載和分享為主,文章觀(guān)點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權請聯(lián)系QQ:712375056 進(jìn)行舉報,并提供相關(guān)證據,一經(jīng)查實(shí),將立刻刪除涉嫌侵權內容。
Copyright ? 2009-2021 56dr.com. All Rights Reserved. 特網(wǎng)科技 特網(wǎng)云 版權所有 珠海市特網(wǎng)科技有限公司 粵ICP備16109289號
域名注冊服務(wù)機構:阿里云計算有限公司(萬(wàn)網(wǎng)) 域名服務(wù)機構:煙臺帝思普網(wǎng)絡(luò )科技有限公司(DNSPod) CDN服務(wù):阿里云計算有限公司 中國互聯(lián)網(wǎng)舉報中心 增值電信業(yè)務(wù)經(jīng)營(yíng)許可證B2
建議您使用Chrome、Firefox、Edge、IE10及以上版本和360等主流瀏覽器瀏覽本網(wǎng)站