文中部分圖片來(lái)源為 動(dòng)力節(jié)點(diǎn)-王鶴老師的Spring Boot3.0 視頻講解中。
一、自動(dòng)配置的原理
-
自動(dòng)配置:從類(lèi)路徑中,搜索相關(guān)的 jar,根據(jù) jar 的內(nèi)容,嘗試創(chuàng)建所需的對(duì)象。例如,如果有 MyBatis .jar,Spring Boot 會(huì)嘗試創(chuàng)建 DataSource(根據(jù)配置文件中的url,username,password)連接數(shù)據(jù)庫(kù)。還需要?jiǎng)?chuàng)建 SqlSessionFactory,Dao 接口的代理對(duì)象。這些內(nèi)容不需要開(kāi)發(fā)人員寫(xiě)一行代碼,就能使用 MyBatis 框架了。
-
xxx.imports 文件是自動(dòng)配置類(lèi)列表。 ====> 說(shuō)明有哪些自動(dòng)配置類(lèi)。
-
xxxAutoConfiguration 是自動(dòng)配置類(lèi)。====> @EnableConfigurationProperties({xxxProperties.class}) 將指定的綁定Bean注入到容器中。文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-824161.html
-
xxxProperties 是綁定Bean。 ====> @ConfigurationProperties(prefix = “xxxx”) 說(shuō)明該類(lèi)是一個(gè)綁定Bean。文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-824161.html
二、關(guān)鍵注解和類(lèi)
1.@EnableAutoConfiguration 注解
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import(AutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {
String ENABLED_OVERRIDE_PROPERTY = "spring.boot.enableautoconfiguration";
Class<?>[] exclude() default {};
String[] excludeName() default {};
}
- 開(kāi)啟自動(dòng)配置。將spring和第三方庫(kù)中的對(duì)象創(chuàng)建好,注入到spring容器,避免寫(xiě)XML,去掉樣例代碼。需要使用的對(duì)象,由框架提供
- @EnableAutoConfiguration 通常由 @SpringBootApplication 注解帶入。
2.@Import 注解
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Import {
Class<?>[] value();
}
- @Import:導(dǎo)入類(lèi),注冊(cè)為Bean。@Import 相當(dāng)于 xml 文件中的 。可以導(dǎo)入@Configuration 的類(lèi),實(shí)現(xiàn)了 ImportSelector 接口的類(lèi),ImportBeanDefinitionRegister 接口的類(lèi)。
3.AutoConfigurationImportSelector 類(lèi)
- AutoConfigurationImportSelector 間接實(shí)現(xiàn)了 ImportSelector 接口,導(dǎo)入自動(dòng)配置類(lèi)。
- 自動(dòng)配置從 jar 的指定文件讀取要加載的配置類(lèi)列表(xxxx.imports 文件)。
4.@AutoConfiguration 注解
- 新的注解 @AutoConfiguration,用在自動(dòng)配置類(lèi)的上面。相當(dāng)于增強(qiáng)的 @Configuration,專(zhuān)注自動(dòng)配置類(lèi)。
- @AutoConfiguration 還支持通過(guò) after、afterNames、before 和 benamemes 屬性進(jìn)行自動(dòng)配置排序,決定多個(gè)自動(dòng)配置類(lèi)執(zhí)行的先后順序。
5.其他相關(guān)的注解和類(lèi)
- @Configuration
- @ConfigurationProperties
- @EnableConfigurationProperties
- @ConditionalXXXXX 條件注解
到了這里,關(guān)于Spring Boot 中的自動(dòng)配置(autoconfigure)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!