Springboot使用@Autowired注入Mapper接口编译错误“Could not autowire. No beans of ‘UserMapper‘ type found.“

Posted 二木成林

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Springboot使用@Autowired注入Mapper接口编译错误“Could not autowire. No beans of ‘UserMapper‘ type found.“相关的知识,希望对你有一定的参考价值。

异常

其实不能完全说是异常,因为存在也不会影响程序的正常运行。

原因

@Mapper 注解是 Mybatis 提供的,而 @Autowried 注解是 Spring 提供的,IDEA能理解 Spring 的上下文,但是不能理解Mybatis。

解决

第一种,关闭IDEA的错误提示,不推荐。

现在再查看,变成了橙色警告了

再次说明,不推荐,因为可能会错过一些关键的提示信息。

第二种,设置@Autowired注解的required属性,不推荐。

此时@Autowried 不会再去校验 Mapper 接口是否为空,但是每个注入都需要设置该属性,比较麻烦。

第三种,将@Autowired注解换成@Resource注解,推荐。

第四种,给Mapper接口添加@Component注解或@Repository注解,推荐。

以上是关于Springboot使用@Autowired注入Mapper接口编译错误“Could not autowire. No beans of ‘UserMapper‘ type found.“的主要内容,如果未能解决你的问题,请参考以下文章

SpringBoot 拦截器中无法使用 @Autowired 注入 Service

SpringBoot自行new出的对象中的成员变量不能使用@Autowired注入的解决办法

springboot中如果使用了@Autowired注入了bean,则这个类也要为spring bean,new出来注入的bean为null

spring springboot websocket 不能注入( @Autowired ) service bean 报 null 错误

SpringBoot@Autowired注入静态成员变量报空指针异常

SpringBoot整合mybatis时,使用Autowired注入RedisTemplate时,报错:因有多个bean不知实现哪一个的问题