关于@Autowired注入bean为NULL的解决方案(楼主亲测有效,一条语句搞定)
今天遇见这样一个问题,在使用@Autowired注入类的时候,一直报为NULL的空指针的错误。
- 错误截图
这个CommonService是在其他包中定义的。
那么在另外的包中使用的时候,可能会因为一系列的原因,出现注入失败。
bean为NULL,总得来说还是加载不到Bean。
报错就是空指针
Caused by: java.lang.NullPointerException: null
解决办法
新增一个工具类,从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;
}
}
在使用的时候
private CommonService commonService = SpringContextUtil.getContext().getBean(CommonService.class);
好啦,祝您工作顺利。
还没有评论,来说两句吧...