我遇到的问题是启动定时器,然后在跟数据库交互的地方报错,Exception in thread "Timer-1" java.lang.NullPointerException。后来检查了一下是因为,dataAcquisitionVoMapper没有正常注入,原始代码如下:
package com.hqgd.pms.controller.Timer;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.TimerTask;
import javax.annotation.Resource;
import com.mon.SpringContextUtil;
import com.hqgd.pms.dao.dataAcquisition.DataAcquisitionVoMapper;
public class UpdateTableTimer extends TimerTask {
@Resource
private DataAcquisitionVoMapper dataAcquisitionVoMapper;
// public UpdateTableTimer() {//从bean工厂里拿个实例
// this.dataAcquisitionVoMapper = SpringContextUtil.getBean(DataAcquisitionVoMapper.class);
// }
@Override
public void run() {
// 获取当前时间
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.MINUTE, -1460);
String lastTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(calendar.getTime());
Map param = new HashMap<>();
for (int i = 1; i <= 4; i++) {
param.put("lastTime", lastTime);
param.put("table", "hq_equipment_monitor_data_r" + i);
dataAcquisitionVoMapper.deleter(param);//此处报空指针异常,是因为dataAcquisitionVoMapper没有正常注入
}
for (int i = 1; i <= 4; i++) {
param.put("tabler", "hq_equipment_monitor_data_r" + i);
param.put("tablef", "hq_equipment_monitor_data_f" + i);
dataAcquisitionVoMapper.insertt(param);
}
}
}
报错提示如下:
在线程中为了线程安全,是防注入的,如果要用到这个类,只能从bean工厂里拿个实例。和上面的代码对比,需要添加下面框框里的代码,就是上面代码注释掉的部分,
SpringContextUtil工具类的代码如下:
package com.mon;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.ponent;
/**
* @Description: 获取bean对象的工具类
* @Author: yaorong
* @CreateDate: /12/10
*/
@Component
public class SpringContextUtil implements ApplicationContextAware {
/**
* 上下文对象实例
*/
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SpringContextUtil.applicationContext = applicationContext;
}
/**
* 获取applicationContext
*
* @return
*/
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
/**
* 通过name获取 Bean.
*
* @param name
* @return
*/
public static Object getBean(String name) {
return getApplicationContext().getBean(name);
}
/**
* 通过class获取Bean.
*
* @param clazz
* @param
* @return
*/
public static T getBean(Class clazz) {
return getApplicationContext().getBean(clazz);
}
/**
* 通过name,以及Clazz返回指定的Bean
*
* @param name
* @param clazz
* @param
* @return
*/
public static T getBean(String name, Class clazz) {
return getApplicationContext().getBean(name, clazz);
}
}
好了,问题解决!!!
小小菜鸟,如有不正确之处,请指正!