一、@Mapper和@Repository关系
在SpringBoot和Mybatis项目中,有两种方式为Mapper接口生成动态代理并注册到容器中。
- 使用@MapperScan,为指定目录下的Mapper接口全部生成动态代理实现类,并注册到容器中。
- 在接口上添加@Mapper注解和@Repository注解
- @Mapper的作用是声明该接口需要Mybatis生成动态代理
- @Repository的作用是将该接口注册到容器中,当然由于@Mapper的存在,实际注册的是反向代理的实现类,接口本身不能作为实现类注册到容器中,所以@Repository不能单独声明于Mapper接口上,需要配合@Mapper或@MapperScan
使用@Mapper和@Repository需注意,SpringBoot默认只会扫描启动类所在目录和子目录中的Bean,推荐使用@MapperScan,可以指定任意目录。
二、Could not autowire. No beans of ‘xxxMapper‘ type found原因分析
使用@MapperScan时,IDEA无法识别@MapperScan指定的包扫描路径下有哪些Mapper接口,所以尝试注入Mapper接口时,IDEA认为这个Mapper不存在于容器中,故警告Could not autowire. No beans of ‘xxxMapper‘ type found
,实际不影响启动。
三、解决办法
方法一:配置IDEA忽略该警告
2022版本IDEA
可以调整警告等级,或直接取消勾选关闭检查
Settings -> Editor -> Inspections -> Spring -> Spring Core -> Code -> Incorrect injection point autowiring in Spring bean component
方法二:在接口上添加@Repository
注解
当使用了@MapperScan,该接口本来就已经注册到容器中了,@Repository没实际作用,这里的作用只是告诉IDEA,该接口已经注册到容器中了