@Autowired注解爆红原因及解决方法

@Autowired 爆红现象

@Autowired报错原因分析

@Autowired源码

public @interface Autowired {
          
   
    boolean required() default true;
}

这里说明@Autowired注解必须要注入一个非空的对象 我们看@Autowired注解的包,来自于: 而这个接口:

@Mapper
public interface UserMapper {
          
   
    //添加用户方法(注册功能)
    public int addUser(User user);

}

的包来自于: 所以报错原因可以归结如下: @Autowired注解需要一个非空的对象,而@Autowired是SpringFramework的,但是它引入的对象是Mybatis的@Mapper注解,而idea不能很好地识别Mybatis的注解,所以idea不能确认当前要注入的对象是否为非NULL对象。

解决办法

  1. 使用@Resource注解,这是一个java注解

2. 在idea的setting里把Autowired中error关了

  1. 在mapper层添加上一个SpringFramework的注解,比如@Repository注解
@Mapper
@Repository
public interface UserMapper {
          
   
    //添加用户方法(注册功能)
    public int addUser(User user);

}
经验分享 程序员 微信小程序 职场和发展