工具类的静态方法
关键注解@PostConstruct
因为静态方法会先加载,@Autowired
注解无法在此之前注入,所以如果在静态方法中直接使用taskInfoDao
它是一个null值,所以需要使用@PostConstruct
注解,此注解在@Autowired
之后执行,在init方法中重新给Dao赋值即可
代码
package com.timer.util;
import java.util.Date;
import javax.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.dao.TaskInfoDao;
import com.entity.TaskInfo;
/**
* 定时任务统一方法抽取
* @author chiuke
*/
@Component
public class TaskUtil {
private static TaskUtil taskUtil;
private static final Logger LOGGER = LoggerFactory.getLogger(TaskUtil.class);
@Autowired
private TaskInfoDao taskInfoDao;
@PostConstruct
public void init(){
taskUtil = this;
taskUtil.taskInfoDao = this.taskInfoDao;
}
/**
* 定时任务开始时执行此方法
*
* @param funName
* @return
*/
public static TaskInfo taskStart(String funName) {
TaskInfo taskInfo = new TaskInfo();
Date date = new Date();
taskInfo.setFunName(funName);
taskInfo.setFunNameLock(funName);
taskInfo.setCreateTime(date);
try {
taskUtil.taskInfoDao.insert(taskInfo);
} catch (Exception e) {
LOGGER.error("插入数据失败");
return null;
}
return taskInfo;
}
}