- A+
所属分类:未分类
缘由
简单来说就是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("任务执行成功"); } }
- 安卓客户端下载
- 微信扫一扫
- 微信公众号
- 微信公众号扫一扫