文章目录

在一次多模块系统项目搭建时,为了扫描到引入的其他模块中的Bean,用到了@ComponentScan标签,却引发了一些其他问题,继续深入了解了下@SpringBootApplication与@ComponentScan标签的作用,总结如下:

具体案例是:
TestController实现了ApplicationListener,当Spring容器启动完成后,会调用这个方法,这个方法里打印了一条日记,当然前提是TestController必须被加载到Spring容器中,所以我们可以通过这条日志判断这个类是否被Spring加载。

(1)只有@SpringBootApplication,日志正常打印
@SpringBootApplication默认会扫描同包及子包,所以TestController被扫描,打印日志
(2)存在@SpringBootApplication和一个@ComponentScan注解,不打印日志
@ComponentScan注解会先被处理,然后返回,使得@SpringBootApplication中的配置没有生效
(3)存在@SpringBootApplication和多个@ComponentScan注解,日志正常打印
多个@ComponentScan注解会被整合成一个@ComponentScans注解,不影响@SpringBootApplication中配置的正确读取

解决方法:
使用@ComponentScans注解,而不是直接使用@ComponentScan注解

1
2
3
4
5
6
7
8
9
10
11
@SpringBootApplication
@ComponentScans({
@ComponentScan("com.iceberg.springboot.biz"),
@ComponentScan("com.iceberg.springboot.manager")
})
public class WebApplication {

public static void main(String[] args) {
SpringApplication.run(WebApplication.class, args);
}
}

参考地址:https://bbs.huaweicloud.com/blogs/138036

文章目录