現象
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,而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
)

添加指定掃描的包
若當前情況下,其他類不在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
分析:掃描包的范圍變大了。
