原创

解决 Could not autowire. No beans of 'UserDao' type found 问题


前言:今天在完善项目的时候发现使用@Autowired注入的Dao层依赖出现报错,但是不影响项目的运行,看着着实心烦,遂解决了

问题

在这里插入图片描述

这个错误不影响项目运行,但是它看着很烦...

分析

Dao层代码:

@Mapper
public interface UserDao {

    User findUserById(@Param("userId") int userId);

    User findUserByNickname(@Param("nickname") String nickname);

    User login(String username,String password);
}

既然项目能运行,证明代码啥的是没错的,@Mapper 注解已将接口的代理类给了 Spring 容器管理,理论上不应该报错。 怀疑是现在使用的 IDEA 版本(2018版的)有点旧,没识别出 @Mapper 注解,然后在项目自动编译的时候,爆出红色波浪线(PS:之前我使用2020版的 IDEA 时也没出现过这个错误)。

解决方法

在 Dao 层接口上加上 @Repository 注解(@Repository 注解是 Spring 的注解,主动标识当前类要交给 Spring 容器管理,然后生成 Dao 层的 bean)。

IDEA
End
  • 作者:小关同学(联系作者)
  • 发表时间:2022-02-23 11:17
  • 版权声明:自由转载-非商用-非衍生-保持署名(创意共享3.0许可证)
  • 公众号转载:请在文末添加作者博客链接
  • 问题交流(QQ群)