一次springboot applicationContext.getBean(clazz)空指針


現象:

  windows本地環境啟動

@Autowired
private CfgCityMapper cfgCityMapper;

public CfgCityServiceImpl() {
    //實例化時直接查詢全部地市
    allCityList = SpringContext.getBean(CfgCityMapper.class).queryAllWithCfgCounty();
}

 


本地啟動不會報錯

打成jar啟動,部署linux或者本地部署,報錯NullPointException ,改成
@PostConstruct
public void init(){
    //實例化時直接查詢全部地市
    allCityList = SpringContext.getBean(CfgCityMapper.class).queryAllWithCfgCounty();
}

 

還是異常,改成
@PostConstruct
public void init(){
    //實例化時直接查詢全部地市
    allCityList =cfgCityMapper.queryAllWithCfgCounty();
}

 

沒有錯
原因:待分析
20200628
此類型錯誤再次出現,初步分析
1、ApplicationContext.getBean()不能在Bean的生命周期中(構造函數、BeanPostProcessor、InitializingBean均不可),
當前解決方案是在方法里定義init方法初始AppliccationContext.getBean(),設置相關屬性
2、之所以在打成jar啟動不行,本地啟動卻可以,可能是根據倆者加載的速度不同?如果在 InitializingBean 里先sleep幾秒,再獲取Bean,也是不會報錯的
但是bean的加載順序應該有一定的規律的才對,不會收加載速度影響吧,待分析


 
        
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM