quartz autowired null Service无法注解,Job无法执行
Posted mr_raptor
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了quartz autowired null Service无法注解,Job无法执行相关的知识,希望对你有一定的参考价值。
类似所谓的解决方案很多,但是大部分都试了下,不太好用。
最终通过,Stackoverflow解决:
https://stackoverflow.com/questions/48577810/how-to-autowired-in-quartz?r=SearchResults
原因,quartz和Spring容器上下文context不在一起,而job里需要通过autowired来获得Service对象进行业务操作。
1. 先通过BeanFactory来将两个context打通,使得quartz使用Spring的context
@Component
public final class ApplicationContextHolder extends SpringBeanJobFactory implements ApplicationContextAware
private static ApplicationContext context;
private transient AutowireCapableBeanFactory beanFactory;
@Override
public void setApplicationContext(ApplicationContext ctx) throws BeansException
beanFactory = ctx.getAutowireCapableBeanFactory();
context = ctx;
@Override
protected Object createJobInstance(final TriggerFiredBundle bundle) throws Exception
final Object job = super.createJobInstance(bundle);
beanFactory.autowireBean(job);
return job;
public static ApplicationContext getContext()
return context;
2. 在Config里,使用Spring Context创建JobFactory
@Configuration
public class QuartzSchedulerConfiguration
@Autowired
private ApplicationContext applicationContext;
/**
* Create the job factory bean
* @return Job factory bean
*/
@Bean
public JobFactory jobFactory()
ApplicationContextHolder jobFactory = new ApplicationContextHolder();
jobFactory.setApplicationContext(applicationContext);
return jobFactory;
/**
* Create the Scheduler Factory bean
* @return scheduler factory object
*/
@Bean
public SchedulerFactoryBean schedulerFactory()
SchedulerFactoryBean factory = new SchedulerFactoryBean();
factory.setAutoStartup(true);
factory.setSchedulerName("My Scheduler");
factory.setOverwriteExistingJobs(true);
factory.setJobFactory(jobFactory());
return factory;
以上是关于quartz autowired null Service无法注解,Job无法执行的主要内容,如果未能解决你的问题,请参考以下文章
Spring boot下@Autowired 注入为 NULL的问题