一次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的加载顺序应该有一定的规律的才对,不会收加载速度影响吧,待分析



 
原文地址:https://www.cnblogs.com/jaxlove-it/p/12554176.html