@Autowired注解使用正确不影响程序运行但是爆红

在使用idea的@Autowired注解注入Mapper文件时,有时会标红,但是不影响项目运行,那么是什么原因呢

原因

先看一下@Autowired源码:

 
@Target({ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Autowired {
	/**
	 * Declares whether the annotated dependency is required.
	 * <p>Defaults to {@code true}.
	 */
	boolean required() default true;

默认值为true说明@Autowired注解必须要注入一个非空的对象,@Autowired注解的包,来自于:

import org.springframework.beans.factory.annotation.Autowired;

@Mapper的包来自于:

import org.apache.ibatis.annotations.Mapper;

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

引申:如果把@Autowired注解的默认值设为false也不会报错

解决方案

1).使用@Resource注解,这是一个java注解;
2).在idea的setting里把Autowired中error关了:在这里插入图片描述
3).在mapper层添加上一个SpringFramework的注解,比如@Repository注解:

 
@Mapper 
@Repository
public interface UserMapper {

}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值