Spring Boot 中的自動配置autoconfigure詳解
一、自動配置的原理
自動配置:從類路徑中,搜索相關的 jar,根據(jù) jar 的內(nèi)容,嘗試創(chuàng)建所需的對象。例如,如果有 MyBatis .jar,Spring Boot 會嘗試創(chuàng)建 DataSource(根據(jù)配置文件中的url,username,password)連接數(shù)據(jù)庫。還需要創(chuàng)建 SqlSessionFactory,Dao 接口的代理對象。這些內(nèi)容不需要開發(fā)人員寫一行代碼,就能使用 MyBatis 框架了。
- xxx.imports 文件是自動配置類列表。 ====> 說明有哪些自動配置類。
- xxxAutoConfiguration 是自動配置類。====> @EnableConfigurationProperties({xxxProperties.class}) 將指定的綁定Bean注入到容器中。
- xxxProperties 是綁定Bean。 ====> @ConfigurationProperties(prefix = “xxxx”) 說明該類是一個綁定Bean。
二、關鍵注解和類
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 {}; }
- 開啟自動配置。將spring和第三方庫中的對象創(chuàng)建好,注入到spring容器,避免寫XML,去掉樣例代碼。需要使用的對象,由框架提供
- @EnableAutoConfiguration 通常由 @SpringBootApplication 注解帶入。
2.@Import 注解
@Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface Import { Class<?>[] value(); }
@Import:導入類,注冊為Bean。@Import 相當于 xml 文件中的 ??梢詫隌Configuration 的類,實現(xiàn)了 ImportSelector 接口的類,ImportBeanDefinitionRegister 接口的類。
3.AutoConfigurationImportSelector 類
- AutoConfigurationImportSelector 間接實現(xiàn)了 ImportSelector 接口,導入自動配置類。
- 自動配置從 jar 的指定文件讀取要加載的配置類列表(xxxx.imports 文件)。
4.@AutoConfiguration 注解
- 新的注解 @AutoConfiguration,用在自動配置類的上面。相當于增強的 @Configuration,專注自動配置類。
- @AutoConfiguration 還支持通過 after、afterNames、before 和 benamemes 屬性進行自動配置排序,決定多個自動配置類執(zhí)行的先后順序。
5.其他相關的注解和類
- @Configuration
- @ConfigurationProperties
- @EnableConfigurationProperties
- @ConditionalXXXXX 條件注解
到此這篇關于Spring Boot 中的自動配置autoconfigure的文章就介紹到這了,更多相關Spring Boot 自動配置內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Java開發(fā)工具Eclipse使用技巧全局搜索和更替
這篇文章主要介紹了Java開發(fā)工具Eclipse使用技巧全局搜索和更替,小編覺得還是挺不錯的,具有一定借鑒價值,需要的朋友可以參考下2018-01-01