SpringBoot | @ComponentScanner註解預設掃描包範圍分析
阿新 • • 發佈:2022-04-21
現象
xxx
分析
在SpringBoot中使用@ComponentScanner
註解進行元件掃描載入類時,預設的掃描範圍是啟動類([ProjectName]Application
)所在包(直接父包)的子包。也即需要被掃描的包下的類要位於啟動類所在路徑下。
正確情況:
src
main
java
com.nathan.test
testApplication
controller
testController
分析: testController
位於testApplication
所在包com.nathan.test
下。
啟動類所在路徑: com/nathan/test/
錯誤情況:
src
main
java
com.nathan.test
application
testApplication
controller
testController
分析:此時testApplication
所在包為application
,而controller
和application
無包含關係,則掃描不到controller
下面的包,會造成bean建立失敗。
啟動類所在路徑: com/nathan/test/application
。
點選註解,檢視註解程式碼
// SpringBootApplication.class @ComponentScan( excludeFilters = {@Filter( type = FilterType.CUSTOM, classes = {TypeExcludeFilter.class} ), @Filter( type = FilterType.CUSTOM, classes = {AutoConfigurationExcludeFilter.class} )} public @interface SpringBootApplication { @AliasFor( annotation = EnableAutoConfiguration.class )