在非controller层中依赖注入为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 ;
    }
}
posted @ 2022-10-24 22:23  热心邻居老王  阅读(181)  评论(0编辑  收藏  举报