您的位置:首頁技術文章
文章詳情頁

springboot bean掃描路徑的實現

瀏覽:17日期:2023-03-27 11:43:44

1:默認掃描啟動類所在路徑下所有的bean

2:可以在啟動類中添加注解,手動指定掃描路徑:

@ComponentScan(basePackages = {'com.xxx.service1.*','com.xxx.service2.**'})

補充:SpringBoot 是如何通過 @SpringBootApplication 掃描項目中的 Bean

原因

首先因為 XXXXXXXApplication 附帶 @SpringBootApplication 注解,而 @SpringBootApplication 注解的層次如下:

SpringBootApplication----@Inherited----@SpringBootConfiguration--------@Configuration----@EnableAutoConfiguration--------@Inherited--------@AutoConfigurationPackage------------@Inherited------------@Import(AutoConfigurationPackages.Registrar.class)--------@Import(AutoConfigurationImportSelector.class)----@ComponentScan--------@Repeatable(ComponentScans.class)實現

可以看到 @SpringBootApplication 繼承 @ComponentScan 與 @Configuration 用處如下;

掃描方法開始流程:

springboot bean掃描路徑的實現

主要觀察黃色方塊的方法,是具體掃描路徑的地方,具體實現流程如下:

springboot bean掃描路徑的實現

獲取 File 目錄下的所有以 class 為結尾的文件后,掃描工作就完成了, 剩下的就是 spring 判斷是否要管理此類的邏輯(例如:該類是否存在 @Component )

以上為個人經驗,希望能給大家一個參考,也希望大家多多支持好吧啦網。如有錯誤或未考慮完全的地方,望不吝賜教。

標簽: Spring
相關文章:
国产综合久久一区二区三区