我遇到的問題是啓動定時器,而後在跟數據庫交互的地方報錯,Exception in thread "Timer-1" java.lang.NullPointerException。後來檢查了一下是由於,dataAcquisitionVoMapper沒有正常注入,原始代碼以下:java
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.hqgd.pms.common.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<String, Object> 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工具類的代碼以下:spring
package com.hqgd.pms.common; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Component; /** * @Description: 獲取bean對象的工具類 * @Author: yaorong * @CreateDate: 2018/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 <T> * @return */ public static <T> T getBean(Class<T> clazz) { return getApplicationContext().getBean(clazz); } /** * 經過name,以及Clazz返回指定的Bean * * @param name * @param clazz * @param <T> * @return */ public static <T> T getBean(String name, Class<T> clazz) { return getApplicationContext().getBean(name, clazz); } }
好了,問題解決!!!數據庫
小小菜鳥,若有不正確之處,請指正!安全