1. 程式人生 > 實用技巧 >在非controller、service裡@Resource注入service為null解決方法

在非controller、service裡@Resource注入service為null解決方法

我們在專案中,一般在controller層中注入service介面,在service層中注入其它的service介面或者mapper介面都是可以的,但是如果我們要在我們自己封裝的Utils工具類中或者非controller普通類中使用@Resource或@Autowried註解注入Service或者Mapper介面就會出現注入為null的問題。下面解決方案:

方法1:使用靜態變數 加 @PostConstruct 解決。

@Component //關鍵1
public class ArticlesReceiver {

    @Resource
    private  WechatArticlesTempService wechatArticlesTempService;

    public static ArticlesReceiver articlesReceiver; //關鍵2

    @PostConstruct //關鍵3
    public void init(){
        articlesReceiver = this;
    }

    public WechatArticlesTemp getResposeArticlesBoby(String mediaId) {
      WechatArticlesTemp articlesTemp = articlesReceiver.wechatArticlesTempService.getById(mediaId); //關鍵4
      return articlesTemp ;
    }
}

方法2:使用靜態變數,加set注入

@Component //關鍵1
public class ArticlesReceiver {
 
    private static WechatArticlesTempService wechatArticlesTempService; //關鍵2
 
    @Autowired  //關鍵3
    public void setWechatArticlesTempService (WechatArticlesTempService wechatArticlesTempService){
          ArticlesReceiver.wechatArticlesTempService = wechatArticlesTempService;
    }
         
    public WechatArticlesTemp getResposeArticlesBoby(String mediaId) {
      WechatArticlesTemp articlesTemp = wechatArticlesTempService.getById(mediaId); //關鍵4
      return articlesTemp ;
    }
}

方法3:程式碼注入 , SpringContectHolder類將用到的類的class讀入讓後再呼叫類中方法

@Component //關鍵1
public class ArticlesReceiver {
 
    private static WechatArticlesTempService wechatArticlesTempService =  SpringContextHolder.getBean(WechatArticlesTempService.class); //關鍵2
 
    public WechatArticlesTemp getResposeArticlesBoby(String mediaId) {
      WechatArticlesTemp articlesTemp = wechatArticlesTempService.getById(mediaId); //關鍵3
      return articlesTemp ;
    }
}

參考https://www.cnblogs.com/04241202-nan/p/11940610.html