在构造方法中使用springcontextUtil中获取bean报错Caused by: java.lang.NullPointerException: ApplicationContext为null导致的空指针
启动mg工程时报错了,居然是spring容器中的AnnotationConfigServletWebServerApplicationContext初始化失败,使用的是AnnotionContext,在eclipse中debug启动时Initializing Spring embedded WebApplicationContext成功,使用SentinelWebAutoConfiguration启动,以下内容中注释掉的是错误的:
// public DcDictProvider() {
// if(mcGatherDao == null) {
// mcGatherDao = SpringContextUtil.getBean(MCGatherDao.class);
// }
// }
@PostConstruct
public void setMCGatherDao() {
if (mcGatherDao == null) {
mcGatherDao = SpringContextUtil.getBean(MCGatherDao.class);
}
}
在Spring Boot工程中遇到启动时的NullPointerException,源于尝试在构造方法中通过SpringContextUtil获取Bean,该方法在非Spring管理的类中可能导致ApplicationContext为null。问题在于不应在构造方法中直接依赖Spring管理的Bean。改为使用@PostConstruct注解的方法来初始化Bean,确保在ApplicationContext初始化完成后执行。修复后的代码在应用启动时能正确注入MCGatherDao。
1万+

被折叠的 条评论
为什么被折叠?



