In general, the object injected with the autowired annotation in the quartz job is empty, and we are going to use the Adaptablejobfactory class provided by Spring-quartz.
To customize a class:
[Java]View PlainCopy
- Public class Jobfactory extends Adaptablejobfactory {
- @Autowired
- private Autowirecapablebeanfactory capablebeanfactory;
- @Override
- protected Object createjobinstance (Triggerfiredbundle bundle) throws Exception {
- //method of calling parent class
- Object jobinstance = super.createjobinstance (bundle);
- //To inject
- Capablebeanfactory.autowirebean (jobinstance);
- return jobinstance;
- }
- }
Then configure in spring:
[HTML]View PlainCopy
- <!--Factorybean of scheduled tasks, configure other config---
- <Bean id="jobfactory" class="Com.xx.job.JobFactory"></Bean>
- <Bean id= "schedulerfactorybean" class=" Org.springframework.scheduling.quartz.SchedulerFactoryBean ">
- < name= "jobfactory" ref="Jobfactory"> </Property>
- </Bean>
At this point, when we define the class to inherit the job, we can use autowired to inject the service object:
[Java]View PlainCopy
- Public class Test1job implements Job {
- public Final Logger log = Logger.getlogger (this.getclass ());
- @Autowired
- private Jobtaskservice Jobtaskservice;
- public Void execute (jobexecutioncontext context) throws jobexecutionexception {
- //Update last execution time and next scheduled execution time
- Date nextprocesstime = Context.getnextfiretime ();
- Schedulejob job = (schedulejob) context.getjobdetail (). Getjobdatamap (). Get ("schedulejob");
- Job.setnextprocesstime (Nextprocesstime);
- Jobtaskservice.updatetaskbyjobname (Job);
- //Business logic
- System.out.println ("22222222222222222222:");
- }
- }
Inject spring objects into the quartz job!