解决办法:
Field surveyTypeService in com.XXX.controller.XXX required a bean of type ‘com.XXX.mapper.xxx’ that could not be found
一、 报错信息:
Description:
Field surveyTypeService in com.beyond.system.survey.controller.SurveyTypeController required a bean of type ‘com.beyond.system.survey.mapper.SurveyTypeMapper’ that could not be found.
The injection point has the following annotations:
- @org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type ‘com.beyond.system.survey.mapper.SurveyTypeMapper’ in your configuration.
二、解决办法:
com.XXX.mapper.xxx 接口添加注解:@repository和 @mapper
@Mapper
@Repository
public interface SurveyTypeMapper extends BaseMapper<SurveyType> {}
三、 此两个注解作用、区别:
参考:https://blog.csdn.net/Sunshineoe/article/details/115447746
https://blog.csdn.net/qq_44421399/article/details/109825479
1、@Repository
@Repository 是 Spring 的注解,用于声明一个 Bean。@Repository单独使用没用。可以这样理解,注解放在接口上本来就没有意义,spring中在mapper接口上写一个@Repository注解,只是为了标识,要想真正是这个接口被扫描,必须使用@MapperScannerConfigurer
<!-- 配置 Mapper 扫描器 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.shenlei.mapper"/>
</bean>
这段配置会扫描com.shenlei.mapper包下所有的接口,然后创建各自的动态代理类。
与spring集成可分三个步骤:
1、把java类对应的Mapper接口类纳入spring总的IOC容器。
2、把Java类对应的XML命名空间添加到Mybatis中的Configuration类中的mapperRegistry(用于管理Mybatis的Mapper)
3、使用spring中的IOC容器拓展FactoryBean获取到Mapper的实例。(第一步纳入spring只是接口)
2、 @Mapper
@Mapper是mybatis自身带的注解。在spring程序中,mybatis需要找到对应的mapper,在编译时生成动态代理类,与数据库进行交互,这时需要用到@Mapper注解。
但是有时候当我们有很多mapper接口时,就需要写很多@Mappe注解,这样很麻烦,有一种简便的配置化方法便是在启动类上使用@MapperScan注解。
这样可以自动扫描包路径下所有的mapper接口,从而不用再在接口上添加任何注解。
3、相同点:
@Mapper和@Repository都是作用在dao层接口,使得其生成代理对象bean,交给spring 容器管理
对于mybatis来说,都可以不用写mapper.xml文件
4、不同点:
1、@Mapper不需要配置扫描地址,可以单独使用,如果有多个mapper文件的话,可以在项目启动类中加入@MapperScan(“mapper文件所在包”)
2、@Repository不可以单独使用,否则会报错误,要想用,必须配置扫描地址(@MapperScannerConfigurer)
四、解决使用@mapper接口时,注入mapper爆红问题
在idea中单独使用@Mapper注解,在@Autowired时,idea会提示找不到bean,但是不影响运行,如果想消除爆红,可以将@Mapper注解跟@Repository注解一起用,这样便可消除爆红。
@Mapper
@Repository
public interface SurveyTypeMapper extends BaseMapper<SurveyType> {}