SpringBoot | @ComponentScan()注解默認掃描包范圍分析


現象

xxx

默認掃描范圍

在SpringBoot中使用@ComponentScan()注解進行組件掃描加載類時,默認的掃描范圍是啟動類([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
    )

image

添加指定掃描的包

若當前情況下,其他類不在application類所在包的子包中,但還需掃描作為bean供創建對象,則可以手動添加掃描的包。
使用@ComponentScan("包路徑")

//添加要掃碼的包 ,此時為 com.nathan
@ComponentScan("com.nathan")
@SpringBootApplication
public class WikiApplication {
//1.創建log日志
    private static final Logger LOG = LoggerFactory.getLogger(WikiApplication.class);

文件結構:

	src
		main
			java
				com.nathan.test
					application
						testApplication
					controller
						testController

分析:掃描包的范圍變大了。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM