Spring boot quartz
Spring can't inject spring bean when using Quartz in Spring .
The job in Quartz is reflected by the instance and is not managed by spring. As a result, the spring in the job cannot be injected into the spring.
solution
Quartz has a JobFactory
interfaces for generating a Job class instance.
This interface may be useful to users who wish to have their applications generate Job instances through some special mechanism, such as giving dependency injection operations.
We need to do is implement a JobFactory
class interface, dependency injection.
In the spring, if not dependent on spring-context-support
circumstances
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
twenty one
twenty two
twenty three
twenty four
25
26
27
28
29
30
31
32
33
34
35
|
Public class QuartzService implements ApplicationContextAware {
Private transient ApplicationContext applicationContext;
Public Scheduler getScheduler () throws SchedulerException {
SchedulerFactory schedulerFactory = new org.quartz.impl.StdSchedulerFactory();
Scheduler scheduler = schedulerFactory.getScheduler();
AutowiringSpringBeanJobFactory autowiringSpringBeanJobFactory = new AutowiringSpringBeanJobFactory();
autowiringSpringBeanJobFactory.setApplicationContext(applicationContext);
scheduler.setJobFactory(autowiringSpringBeanJobFactory);
Return scheduler;
}
Public void setApplicationContext (ApplicationContext applicationContext) throws BeansException {
This .applicationContext = applicationContext;
}
// Custom implementation of JobFactory
Class AutowiringSpringBeanJobFactory extends AdaptableJobFactory {
Private transient AutowireCapableBeanFactory autowireCapableBeanFactory;
Public void setApplicationContext ( final ApplicationContext context) {
autowireCapableBeanFactory = context.getAutowireCapableBeanFactory();
}
Public Object createJobInstance ( final TriggerFiredBundle bundle) throws Exception {
Final Object job = super .createJobInstance(bundle);
autowireCapableBeanFactory.autowireBean(job); //the magic is done here
Return job;
}
}
}
|
We have a dependency in the spring spring-context-support
case
1
2
3
4
5
6
7
8
9
10
11
12
13
|
Public class SpringJobFactory extends AdaptableJobFactory {
Private AutowireCapableBeanFactory capableBeanFactory;
Protected Object createJobInstance (TriggerFiredBundle bundle) throws Exception {
Object jobInstance = super .createJobInstance(bundle);
capableBeanFactory.autowireBean(jobInstance);
Return jobInstance;
}
}
|
1
2
3
4
5
6
7
8
9
10
11
12
|
Public class SchedulerConfig {
Private SpringJobFactory springJobFactory;
Public SchedulerFactoryBean schedulerFactoryBean () {
SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();
schedulerFactoryBean.setJobFactory(springJobFactory);
Return schedulerFactoryBean;
}
}
|
Because SchedulerFactoryBean
a FactoryBean Thus, when in use, can be injected directly into Scheduler
the next step.
USEFUL RESOURCES: