今天遇見這樣一個問題,在使用@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);
好啦,祝您工作順利。