BankDAO类内容如下:
package com.wiseco.engine.dao;


Controller中内容:
cacheTableMap.get(tableName)值为:com.wiseco.engine.dao.BankDAO

结果调用controller执行refreshCache函数时报空指针异常,通过debug模式跟踪发现以下地方cacheJob对象是null。

分析后原因如下:controller中的对象是通过反射创建的新对象,不是spring容器中的对象,而cacheJob是通过autoWired注入到spring容器中的对象中的。因此对于新创建的对象cacheJob对象就是空值。
解决办法一:conroller中还是使用springboot自己的对象
写的工具类为SpringUtil,实现ApplicationContextAware接口,并加入Component注解,让spring扫描到该bean
@Component
public class SpringUtil implements ApplicationContextAware {
private static Logger logger = LoggerFactory.getLogger(SpringUtil.class);
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
if(SpringUtil.applicationContext == null) {
SpringUtil.applicationContext = applicationContext;
}
logger.info("ApplicationContext配置成功,applicationContext对象:"+SpringUtil.applicationContext);
}
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
public static Object getBean(String name) {
return getApplicationContext().getBean(name);
}
public static <T> T getBean(Class<T> clazz) {
return getApplicationContext().getBean(clazz);
}
public static <T> T getBean(String name,Class<T> clazz) {
return getApplicationContext().getBean(name,clazz);
}
}
修改代码如下,controller调用成功,不再有空指针异常

本文介绍在Spring Boot应用中,如何解决因反射创建对象而非通过Spring容器导致的空指针异常问题。通过使用自定义工具类SpringUtil,实现了在控制器中正确获取和使用由Spring管理的对象。
1万+

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



