启动spring boot项目时,第三方jar包扫描不到的问题

讲述一下遇到的问题:

在启动类Application上使用@ComponentScan 这个注解来扫描第三方的包,然后就会出现报错。异常就是无法加载本地的bean,但是可以加载到第三方的bean;

了解过spring boot启动流程的都知道,Springboot启动类注解@SpringBootApplication = @Configuration + @EnableAutoConfiguration + @ComponentScan。其中扫描包的范围默认为启动类所在包和子包。如果我们需要扫描其他模块的包或者第三方的jar包,我们就要单独使用@ComponentScan注解扫描,或者直接在@SpringbootApplication注解中指定扫描的第三方路径。

但是,如果@SpringBootApplication和@ComponentScan注解在一个启动类中共存 ,那么**@SpringBootApplication注解的扫描的作用将会失效**,也就是说不能够扫描启动类所在包以及子包了,因为它被@ComponentScan注解中指定的包扫描覆盖了。

在这个启动类中,我们加上了@ComponentScan注解,并在这个注解上指定了一个路径,那么现在spring boot项目启动时就只会扫描com.zq.testspringboot包下的内容。不会再默认扫描启动类所在的包及其子包。

解决办法:

1、@SpringBootApplication和@ComponentScan注解在一个启动类中共存时,@ComponentScan中必须指定所有需要扫的包,不然没有指定的包就不会扫描到。这样就可以解决问题了,即可以扫描第三方jar包又可以扫描本地的路径

2、使用@ComponentScans注解,配置多个ComponentScan注解。

这种方法与之前第一种方法类似,都是在ComponentScan注解中指定所有要扫描的路径,不管是本地的还是第三方引入的。

3、配置包扫描建议单独 建立一个配置类加上@Configuration注解和@ComponentScan注解配置要扫描的包,并放到启动类所在包的子包下。

总之,只要不在同一个类中同时使用@SpringBootApplication注解和@ComponentScan注解就可以保证写的扫描包路径不被覆盖掉

相关推荐
2601_9498177219 小时前
Spring Boot3.3.X整合Mybatis-Plus
spring boot·后端·mybatis
uNke DEPH19 小时前
Spring Boot的项目结构
java·spring boot·后端
zhenxin012220 小时前
Spring Boot 3.x 系列【3】Spring Initializr快速创建Spring Boot项目
spring boot·后端·spring
zhenxin012221 小时前
【wiki知识库】07.用户管理后端SpringBoot部分
spring boot·后端·状态模式
SeSs IZED1 天前
SSM与Springboot是什么关系? -----区别与联系
java·spring boot·后端
勿忘,瞬间1 天前
SpringBoot配置文件
java·spring boot·后端
2601_949814491 天前
Spring Boot中使用Server-Sent Events (SSE) 实现实时数据推送教程
java·spring boot·后端
wellc1 天前
SpringBoot集成Flowable
java·spring boot·后端
tongxh4231 天前
Spring Boot 3.X:Unable to connect to Redis错误记录
spring boot·redis·后端
hERS EOUS1 天前
Spring Boot + Spring AI快速体验
人工智能·spring boot·spring