原代碼
@Service
public class XdsShowServiceImpl implements IXdsShowService {
@Autowired
private ICodeService codeService;
public JSONObject getBaseData(String region){
...
this.codeService.【相關(guān)方法】
}
報(bào)錯(cuò)NullPointException,斷點(diǎn)排查問題徐绑,發(fā)現(xiàn)問題出在codeService注入為null。
解決方案如下:
@Service
public class XdsShowServiceImpl implements IXdsShowService {
@Autowired
private ICodeService codeService;
private static XdsShowServiceImpl xdsShowServiceImpl;
//進(jìn)行初始化bean之前的操作
@PostConstruct
public void init(){
xdsShowServiceImpl = this;
xdsShowServiceImpl .codeService = this.codeService;
}
public JSONObject getBaseData(String region){
...
xdsShowServiceImpl .codeService.【相關(guān)方法】
}
說明:
為類聲明一個(gè)靜態(tài)變量莫辨,方便下一步存儲(chǔ)bean對(duì)象傲茄。
private static XdsShowServiceImpl xdsShowServiceImpl;
通過注解@PostConstruct ,在初始化的時(shí)候初始化靜態(tài)對(duì)象和它的靜態(tài)成員變量codeService衔掸,原理是拿到service層bean對(duì)象烫幕,靜態(tài)存儲(chǔ)下來俺抽,防止被釋放敞映。
@PostConstruct
public void init(){
xdsShowServiceImpl = this;
xdsShowServiceImpl .codeService = this.codeService;
}