Spring quartz Job dependency injection and quartz usage
Spring quartz Job dependency injection usage
I. Problem description:
When Spring is used to integrate quartz for dynamic tasks, when you want to use a service in a job scheduled task, adding annotation @ Component and @ Autowired cannot be injected directly, and the obtained object is Null. The following code:
@Component @PersistJobDataAfterExecution @DisallowConcurrentExecution public class TicketSalePriceLessThanLowestPriceJob implements Job{ @Autowired private XxxService xxxService; }
Ii. solution:
1. Add a custom class (CustomJobFactory) to inherit SpringBeanJobFactory. The Code is as follows:
Import org. quartz. spi. triggerFiredBundle; import org. springframework. beans. factory. annotation. autowired; import org. springframework. beans. factory. config. autowireCapableBeanFactory; import org. springframework. scheduling. quartz. springBeanJobFactory; public class CustomJobFactory extends SpringBeanJobFactory {@ Autowired private extends capableBeanFactory; @ Override protected Object createJobInstance (bundle) throws Exception {// call the parent class method Object jobInstance super =. createJobInstance (bundle); // inject capableBeanFactory. autowireBean (jobInstance); return jobInstance ;}}
2. Configure CustomJobFactory in the spring. xml file as follows:
<bean id="customJobFactory" class="cn.imovie.manage.task.job.CustomJobFactory"></bean>
3. Inject custom mmjobfactory into org. springframework. scheduling. quartz. SchedulerFactoryBean, as follows:
<property name="jobFactory" ref="customJobFactory"></property>
The complete code is as follows:
<! -- Scheduled task configuration start --> <bean id = "scheduler" class = "org. springframework. scheduling. quartz. schedulerFactoryBean "> <property name =" dataSource "ref =" dataSource "> </property> <! -- Optional. The existing Job is updated when QuartzScheduler is started, in this way, you do not need to delete the corresponding records of the qrtz_job_details table after each targetObject modification --> <property name = "overwriteExistingJobs" value = "true"/> <! -- Required. zscheduler is started in a delayed manner. After the application is started, QuartzScheduler is restarted. --> <property name = "startupDelay" value = "10"/> <! -- Set Automatic startup --> <property name = "autoStartup" value = "true"/> <property name = "jobFactory" ref = "customJobFactory"> </property> <property name = "applicationContextSchedulerContextKey" value = "applicationContextKey"/> <property name = "configLocation" value = "classpath: spring-quartz.properties "/> </bean> <! -- Scheduled task configuration end -->
4. Then, you can use @ Autowired to inject the service in the Job task class.
If you have any questions, please leave a message or go to the community on this site for discussion. Thank you for reading this article. Thank you for your support!