定时任务出现这个错误,是因为是因为@Scheduled注解方式级别高于资源注入级别,导致资源注入失败.
示例:
@Component @Lazy(value = false) public class AlertTask { @Autowired IOTDeviceService iOTDeviceService; /** * @Description 定时获取数据更新本地数据 * @param * @throws * @Return void * @Date 2019-11-01 09:15:17 * @Author WangKun **/ @Scheduled(cron = "0/5 * * * * ?")//每两分钟执行一次0 */2 * * * ? public void getEquipmentDataAlert() throws Exception { iOTDeviceService.findxx(); }
报错:2019-11-01 09:31:20.005 [pool-2-thread-1] ERROR o.s.s.s.TaskUtils$LoggingErrorHandler - Unexpected error occurred in scheduled task.
修改:
使用ApplicationContextAware,它实现了这个接口的bean,当spring容器初始化的时候,会自动的将ApplicationContext注入进来
示例:
@Component @Lazy(value = false) public class AlertTask implements ApplicationContextAware { private static ApplicationContext context; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { context = applicationContext; } public static ApplicationContext getApplicationContext() { return context; } public static Object getBean(String name) { return getApplicationContext().getBean(name); } /** * @Description 定时获取数据更新本地数据 * @param * @throws * @Return void * @Date 2019-11-01 09:15:17 * @Author WangKun **/ @Scheduled(cron = "0/5 * * * * ?")//每两分钟执行一次0 */2 * * * ? public void getEquipmentDataAlert() throws Exception { IOTDeviceService iOTDeviceService = (IOTDeviceService)this.getBean("iOTDeviceService");
iOTDeviceService.findxx();
}
启动定时任务正常.
也可以将implements ApplicationContextAware抽出来,封装一个工具类.
package com.harmonywisdom.ajproduct.ajproduct.task.util; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; /** * @Description 定时任务service注入工具 * @Author WangKun * @Date 2019/10/31 17:22 * @Version */ public class TaskUtil implements ApplicationContextAware { private static ApplicationContext context; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { context = applicationContext; } public static ApplicationContext getApplicationContext() { return context; } public static Object getBean(String name) { return getApplicationContext().getBean(name); } }