关于@Autowired注入bean为NULL的解决方案(楼主亲测有效,一条语句搞定)

今天遇见这样一个问题,在使用@Autowired注入类的时候,一直报为NULL的空指针的错误。

  1. 错误截图
    这个CommonService是在其他包中定义的。
    那么在另外的包中使用的时候,可能会因为一系列的原因,出现注入失败。
    bean为NULL,总得来说还是加载不到Bean。

在这里插入图片描述

  1. 报错就是空指针
Caused by: java.lang.NullPointerException: null
  1. 解决办法
    新增一个工具类,从Spring的上下文中去取这个Bean.
package com.whalecloud.zsmart.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @Classname SpringContextUtil
 * @Description 此工具类用于从Spring的上下文中去获取到类
 * 调用的时候例如:private CommonService commonService = SpringContextUtil.getContext().getBean(CommonService.class);
 * @Date 2019/11/4 2:00 PM
 * @Created by wangdong
 */
@Component
public final class SpringContextUtil implements ApplicationContextAware {

    private static ApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }

    public static ApplicationContext getContext() {
        return context;
    }

}

  1. 在使用的时候
private CommonService commonService = SpringContextUtil.getContext().getBean(CommonService.class);

在这里插入图片描述

好啦,祝您工作顺利。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值