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
,而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
分析:扫描包的范围变大了。
来源: 博客园
作者: 茶哩哩
文章: 转载请注明原文链接:https://www.cnblogs.com/martin-1/p/16174602.html