SpringBoot簡化配置分析總結
在SpringBoot啟動類中,該主類被@SpringBootApplication所修飾,跟蹤該注解類,除元注解外,該注解類被如下自定注解修飾,
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan
讓我們簡單敘述下它們各自的功能:
- @ComponentScan:掃描需要被IoC容器管理下需要管理的Bean,默認當前根目錄下的
- @EnableAutoConfiguration:裝載所有第三方的Bean
- @SpringBootConfiguration 作用等同于@Configuration
我們來看下@SpringBootConfiguration
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Configuration
public @interface SpringBootConfiguration {
@AliasFor(
annotation = Configuration.class
)
boolean proxyBeanMethods() default true;
}
可以看到該注解類內包含與@Configuration,其作用與@Configuration并無太大區別,只是多了層屬性嵌套,
故: @SpringBootConfiguration + @ComponentScan
將根目錄下所有被**@Controller、@Service、@Repository、@Component**等所修飾的類交給IoC容器管理,
那么重點來了,@EnableAutoConfiguration是如何裝載第三方Bean的呢?讓我們跟蹤下它的原始碼,
首先我們可以看到該類被如下注解修飾:
@AutoConfigurationPackage
@Import({AutoConfigurationImportSelector.class})
我們先關注下AutoConfigurationImportSelector這個組件,
// 批量匯入第三方的一些Bean
@Import({AutoConfigurationImportSelector.class})
其中該組件的selectImports(AnnotationMetadata annotationMetadata)方法,掃描所有需要被管理的第三方Bean并交給IoC容器進行管理,
那么SpringBoot又是如何取感知第三方的Bean檔案呢?
SpringBoot和第三方Bean之間存在一定的規定,即通過對于相應依賴的Jar包中可能存在一個spring.factories檔案,在該檔案中就記錄了需要被IoC容器管理的Bean檔案路徑,SpringBoot通過該檔案確定需要IoC管理的Bean檔案位置,對于spring-boot-autoconfiguration的spring.factories檔案中,記錄著大量xxxAutoConfiguration的類檔案位置,這些類都被@Configuration注解標識,即這些配置類會配置多個Bean從而解決spring.factories可能產生的臃腫問題,
Tomcat的加載時機
對于SpringBoot來說它特點不僅是簡化配置,還有內嵌容器等特點,那么就有必要探討Tomcat容器的加載時機,在spring-boot-autoconfiguration的spring.factories檔案中存在ServletWebServerFactoryAutoConfiguration配置類的路徑,該類會在專案啟動時將默認的Tomcat容器已@Bean的方式加載入IoC容器內部,
SpringBoot是如何集中配置呢?
談論這個問題前我們不妨先按照之前yml或properties的檔案配置下
server:
port: 8080
通過IDE,跟蹤到port所配置的成員變數所在類,發現該類被@ConfigurationProperties所修飾,該注解就是將yml或properties中配置按照對應前綴注入到指定類的成員變數,該注解具體實作感興趣的小伙伴們可以去如下鏈接學習,@ConfigurationProperties實作原理與實戰
@ConfigurationProperties(prefix = "server", ignoreUnknownFields = true)
public class ServerProperties {
private Integer port;
*******
}
下面兩個代碼和前述作用大致相同
environment.getProperty("xxx");
@Value("${xxx}")
已經知道了SpringBoot如何簡化配置,那么我們也可以自己來實作一個starter交給SpringBoot來使用,只要在對應Jar包中添加spring.factories檔案,在其中添加如下代碼,
org.springframework.boot.autoconfigure.EnableAutoConfiguration=xxxAutoConfiguration
大家若有時間還請實作下自己的starter依賴,對加深這部分理解還是很有幫助的,
最后我們在說下最后@SpringBootApplication中@AutoConfigurationPackage這個注解類,發現其中匯入了Registrar組件,
@Import({Registrar.class})
讓我們重點關注registerBeanDefinitions這個方法,該方法最侄訓來到DefaultListableBeanFactory中registerBeanDefinition(String beanName, BeanDefinition beanDefinition)方法,將AutoConfigurationPackages.Registrar.class匯入到IoC容器中,然后將主配置類所在包下所有組件匯入到SpringIoC容器中
怎么樣,在為我們簡化了配置的同時,SpringBoot居然幫我們做了如此多的事情,而我們只需要簡單地集中配置其中一部分的屬性,關于SpirngBoot我們就探討到這里,這些內容是閱讀一些文章,觀看部分講解和原始碼的總結,若有錯誤還請接納與指教,最后感謝各位的閱讀,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/164818.html
標籤:其他
