SpringBoot自動配置原理
來源:酷知科普網 2.55W
SpringBoot自動配置原理
操作方法
(01)SpringBoot啟動的時候載入主配置類,開啟了自動配置功能@EnableAutoConfiguration。
(02)@EnableAutoConfiguration的作用是利用AutoConfigurationImportSelector給容器中匯入一些元件。
(03)可以檢視public String[] selectImports(AnnotationMetadata annotationMetadata)方法的內容。
(04)通過protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes)獲取候選的配置,這個是掃描所有jar包類路徑下"META-INF/ories";
(05)然後把掃描到的這些檔案包裝成Properties物件。
(06)從properties中獲取到s類名對應的值,然後把他們新增在容器中。
(07)整個過程就是將類路徑下"META-INF/ories"裡面配置的所有EnableAutoConfiguration的值加入到容器中。
(08)每一個這樣XXAutoConfiguration類都是容器中的一個元件都加入到容器中,用他們來做自動配置。每一個自動配置類進行自動配置功能,以HttpEncodingAutoConfiguration為例解釋自動配置原理。
(09)根據當前不同的條件判斷,決定這個配置是否生效。