前段时间做了一个基于 SpringBoot和Quartz任务管理系统 (脚手架而已),很多功能不是特别完善,由于工作原因,断断续续一直在更新中,码云上有个小伙伴提问说:Job中service自动注入报错怎么解决?正好之前做的项目中有使用到注入相关的功能,顺便也集成进去。
简单来说就是quartz中的Job是在quartz中实例化出来的,不受spring的管理,所以就导致注入不进去了。
定义SpringJobFactory类:
/** * 解决spring bean注入Job的问题 */ @Component public class SpringJobFactory extends AdaptableJobFactory { @Autowired private AutowireCapableBeanFactory capableBeanFactory; @Override protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception { // 调用父类的方法 Object jobInstance = super.createJobInstance(bundle); // 进行注入 capableBeanFactory.autowireBean(jobInstance); return jobInstance; } }
quartz配置:
/** * quartz配置 * 创建者 科帮网 * 创建时间 2018年4月3日 */ @Configuration public class SchedulerConfig { @Autowired private SpringJobFactory springJobFactory; @Bean(name="SchedulerFactory") public SchedulerFactoryBean schedulerFactoryBean() throws IOException { SchedulerFactoryBean factory = new SchedulerFactoryBean(); factory.setAutoStartup(true); factory.setStartupDelay(5);//延时5秒启动 factory.setQuartzProperties(quartzProperties()); //注意这里是重点 factory.setJobFactory(springJobFactory); return factory; } @Bean public Properties quartzProperties() throws IOException { PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean(); propertiesFactoryBean.setLocation(new ClassPathResource("/quartz.properties")); propertiesFactoryBean.afterPropertiesSet(); return propertiesFactoryBean.getObject(); } /* * quartz初始化监听器 */ @Bean public QuartzInitializerListener executorListener() { return new QuartzInitializerListener(); } /* * 通过SchedulerFactoryBean获取Scheduler的实例 */ @Bean(name="Scheduler") public Scheduler scheduler() throws IOException { return schedulerFactoryBean().getScheduler(); } }
测试任务案例TestJob:
/** * 实现序列化接口、防止重启应用出现quartz Couldn't retrieve job because a required class was not found 的问题 */ public class TestJob implements Job,Serializable { private static final long serialVersionUID = 1L; @Autowired private IJobService jobService; @Override public void execute(JobExecutionContext context) throws JobExecutionException { System.out.println(jobService);//注入jobService 执行相关业务操作 System.out.println("任务执行成功"); } }
项目源码: https://gitee.com/52itstyle/spring-boot-quartz