關於@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);

在這裏插入圖片描述

好啦,祝您工作順利。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章