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

分析:扫描包的范围变大了。

posted @ 2022-04-21 16:08  茶哩哩  阅读(4160)  评论(0编辑  收藏  举报