SpringBoot 中@Autowired 注入失效原因及解决方法

  • Post author:
  • Post category:其他




问题背景:


用户登录模块实现邮箱验证码登录




问题描述


邮件工具类通过@@Autowired注入userMapper调用checkEmailExist(email)接口报java.lang.NullPointerException: null错误




原因分析:

代码中使用new关键字创建实例,导致userMapper注入失效报java.lang.NullPointerException: null错误,代码如下


//邮件工具类
public class SmsHelper {
    @Autowired
    private MailUtil mailUtil;
    @Autowired
    private UserMapper userMapper;

    public  Res<Boolean> sendValiCode(String info, String code){

        Res<Boolean> res = new Res<>();
        if (!ParamsCheck.checkEmail(info)){
            res.setData(true);
            System.out.println("发送验证码:"+code);
            res.setMsg("成功");
        }
        else {
            int count = userMapper.checkEmailExist(info);
            if (count<1) {
                res.setCode(EnumUdsError.EMAIL_TEL_NOT_EXIST.getCode());
                res.setMsg(EnumUdsError.EMAIL_TEL_NOT_EXIST.getMsg());
                return res;
            }
       }
       //发送邮件代码
   }
   
@Service("accountMidService")
public class AccountServiceImpl implements AccountMidService {  
	
	@Override
    public Res<Boolean> sendSmsValiCode(String info){
    	Res<Boolean> res = new Res<>();
        String code = null;
    	//生成验证码
    	......
    	res = new SmsHelper().sendValiCode(info, code);   //通过new实例来进行方法调用,导致该类下的通过@Autowired自动注入的userMapper,注入失效
    	return res;
    }
}



解决方案:

将邮件工具类交给spring容器管理,以注解的方式将对象注入,并调用发送验证码方法

@Service("smsHelper")
public class SmsHelper {}
@Service("accountMidService")
public class AccountServiceImpl implements AccountMidService {  
	@Autowired
    private SmsHelper smsHelper;
    @Override
    public Res<Boolean> sendSmsValiCode(String info){
    	Res<Boolean> res = new Res<>();
        String code = null;
    	//生成验证码
    	......
    	res = smsHelper.sendValiCode(info, code);   //以注入对象的方式进行调用,而不是使用new实例的方式
    	return res;
    }
}



@Autowired 注入失效方式原因总结:


1. 被@Autowired 注解的类所在的包没有被扫描到,springBoot默认Bean装配是在springboot启动类所在包位置从上往下扫描,如果想要注入的类,不属于当前@SpringBootApplication 标注类的子包下,就需要用scanBasePackages 属性手动设置需要扫描包的位置,例如@SpringBootApplication(scanBasePackages = {“com.saas.user.service”,“com.saas.user.mid”})


2. 代码中A类包含以@@Autowired方式注入的属性B,如果A类通过new实例对象则属性B会注入失败



版权声明:本文为qq_34861017原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。