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

曾经终败给现在 2023-05-29 05:11 81阅读 0赞

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

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

在这里插入图片描述

  1. 报错就是空指针

    Caused by: java.lang.NullPointerException: null

  2. 解决办法
    新增一个工具类,从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 {

      1. context = applicationContext;

      }

      public static ApplicationContext getContext() {

      1. return context;

      }

    }

  3. 在使用的时候

    private CommonService commonService = SpringContextUtil.getContext().getBean(CommonService.class);

在这里插入图片描述

好啦,祝您工作顺利。

发表评论

表情:
评论列表 (有 0 条评论,81人围观)

还没有评论,来说两句吧...

相关阅读