在非controller、service里@Resource注入service为null解决方法

我们在项目中,一般在controller层中注入service接口,在service层中注入其它的service接口或者mapper接口都是可以的,但是如果我们要在我们自己封装的Utils工具类中或者非controller普通类中使用@Resource或@Autowried注解注入Service或者Mapper接口就会出现注入为null的问题。下面解决方案:

方法1:使用静态变量 加 @PostConstruct 解决。

 1 @Component //关键1
 2 public class ArticlesReceiver {
 3  
 4     @Resource
 5     private  WechatArticlesTempService wechatArticlesTempService;
 6      
 7     public static ArticlesReceiver articlesReceiver; //关键2
 8      
 9     @PostConstruct //关键3
10     public void init(){
11         articlesReceiver = this;
12     }
13          
14     public WechatArticlesTemp getResposeArticlesBoby(String mediaId) {
15       WechatArticlesTemp articlesTemp = articlesReceiver.wechatArticlesTempService.getById(mediaId); //关键4
16       return articlesTemp ;
17     }
18 }   

 

方法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/huangziwu/p/9450377.html

posted @ 2019-11-27 10:59  止心静坐  阅读(4290)  评论(0编辑  收藏  举报