我们在项目中,一般在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 ; } }