1. 程式人生 > 其它 >SpringBoot | @ComponentScanner註解預設掃描包範圍分析

SpringBoot | @ComponentScanner註解預設掃描包範圍分析

現象

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,而controllerapplication無包含關係,則掃描不到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
    )