Inject spring objects into the quartz job!

Source: Internet
Author: User

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
  1. Public class Jobfactory extends Adaptablejobfactory {
  2. @Autowired
  3. private Autowirecapablebeanfactory capablebeanfactory;
  4. @Override
  5. protected Object createjobinstance (Triggerfiredbundle bundle) throws Exception {
  6. //method of calling parent class
  7. Object jobinstance = super.createjobinstance (bundle);
  8. //To inject
  9. Capablebeanfactory.autowirebean (jobinstance);
  10. return jobinstance;
  11. }
  12. }

Then configure in spring:

[HTML]View PlainCopy
  1. <!--Factorybean of scheduled tasks, configure other config---
  2. <Bean id="jobfactory" class="Com.xx.job.JobFactory"></Bean>
  3. <Bean id= "schedulerfactorybean" class=" Org.springframework.scheduling.quartz.SchedulerFactoryBean ">
  4. < name= "jobfactory" ref="Jobfactory"> </Property>
  5. </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
    1. Public class Test1job implements Job {
    2. public Final Logger log = Logger.getlogger (this.getclass ());
    3. @Autowired
    4. private Jobtaskservice Jobtaskservice;
    5. public Void execute (jobexecutioncontext context) throws jobexecutionexception {
    6. //Update last execution time and next scheduled execution time
    7. Date nextprocesstime = Context.getnextfiretime ();
    8. Schedulejob job = (schedulejob) context.getjobdetail (). Getjobdatamap (). Get ("schedulejob");
    9. Job.setnextprocesstime (Nextprocesstime);
    10. Jobtaskservice.updatetaskbyjobname (Job);
    11. //Business logic
    12. System.out.println ("22222222222222222222:");
    13. }
    14. }

Inject spring objects into the quartz job!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.