欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

多模块项目依赖注入失败Field xxRepository in xxImpl required a bean of type xxRepository that could not be found

程序员文章站 2022-07-06 15:31:57
前言:今天新搭了个多模块服务,controller和service,repository是在不同的模块中的,在controller的模块中导入service,repository的模块依赖,但是在启动时出现错误三连报,下面给出解决思路和方法。1.首先看service错误:Field xxxService in xxxController required a bean of type 'xxxService' that could not be found.很直观,这是service没有被扫描到,导...
错误场景:多模块项目,依赖注入失败

今天新搭了个多模块服务,controller和service,repository是在不同的模块中的,在controller的模块中导入service,repository的模块依赖,但是在启动时出现错误三连报,下面给出解决思路和方法。

1.首先看service错误:

Field xxxService in xxxController required a bean of type 'xxxService' that could not be found.
很直观,这是service没有被扫描到,导致sevice没有被注入。OK,这个简单,可以加@ComponentScan 来解决。注意:使用此注解后controller所在的包也要加到扫描路径中。

@ComponentScan(basePackages = {"com.qixingcxy.basedata","com.qixingcxy.controller"})//扫描 @Service、@Controller 注解
2.启动后又报其他的错误:

Field xxxRepository in xxxImpl required a bean of type 'xxxRepository' that could not be found.
然后我搜了很多博客都是写使用 @ComponentScan 来扫描,然并卵,根本解决不了这个问题。

3.解决repository错误:

从报错确实可以看出是没有扫描repository,但使用 @ComponentScan 注解后没有效果,所以我觉得repository可能不是通过这个注解来扫描的,然后去查扫描repository的注解,果然有此注解,即 @EnableJpaRepositories 注解,ok,把此注解加上,就不报此错误了。

@EnableJpaRepositories(basePackages = "com.qixingcxy.basedata")//扫描 @Repository 注解
4.但是启动又报entity的错了,报错如下:

Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class com.qixingcxy.basedata.goods.Goods

5.解决entity报错:

看完我就笑了,这不是实体类没被扫描吗,和上面一样啊,那就让我找找扫描实体类的注解,果然又让我找到了,即 @EntityScan ,加上后立马程序起飞成功。nice!

@EntityScan(basePackages = "com.qixingcxy.basedata")//扫描 @Entity 注解
6.解决汇总,如果你这三个错误都报了,在启动入口把这三个注解都加上即可:

注意:controller的包也要加在ComponentScan下进行扫描

@ComponentScan(basePackages = {"com.qixingcxy.basedata","com.qixingcxy.controller"})//扫描 @Service、@Controller 注解
@EnableJpaRepositories(basePackages = "com.qixingcxy.basedata")//扫描 @Repository 注解
@EntityScan(basePackages = "com.qixingcxy.basedata")//扫描 @Entity 注解

位置如下图:
多模块项目依赖注入失败Field xxRepository in xxImpl required a bean of type xxRepository that could not be found
说个题外话:如果你遇到错误无法解决,不要拘泥于按报文来搜问题,可以自己分析出一个错误原因,然后按原因来查找解决问题,这样你可能会很快得出你想要的答案。比如repository报错:Field xxxRepository in xxxImpl required a bean of type 'xxxRepository' that could not be found.,搜索无果,此时按错误分析出大概的问题原因,可能是什么造成的,有一个大概的方向,在这里就是可能没有扫描repository造成的,所以可以直接搜用来扫描Repository的注解有哪些,这样就可以进一步确定问题原因。

本文地址:https://blog.csdn.net/m0_37679452/article/details/112527820