Scenario: The job is loaded in the Contextloaderlistener subclass, and Scheduler is set for Jobfactory in the Contextloaderlistener subclass after the @component is declared for the Jobfactory implementation class. (main problem: When the job is called by spring and quartz, the annotation class cannot be read in the job, implementing injection)
Step One:
The code in the Contextinitialized method in the Contextloaderlistener subclass is as follows:
SuperSuper. Getcurrentwebapplicationcontext (); = Applicationcontext.getbean (Scheduler. Class); Try {scheduler.setjobfactory (Applicationcontext.getbean (jobfactory. class catchcatch (schedulerexception E1) {Logger.error (E1.getmessage () , E1); }
Step two: Declare the Jobfactory subclass, and the service class in the job
PackageCom.river.job.listener;ImportOrg.quartz.spi.TriggerFiredBundle;Importorg.springframework.beans.factory.annotation.Autowired;Importorg.springframework.beans.factory.config.AutowireCapableBeanFactory;Importorg.springframework.scheduling.quartz.AdaptableJobFactory;Importorg.springframework.stereotype.Component; @Component Public classMyjobfactoryextendsAdaptablejobfactory {//This object spring will help us to automatically inject, also belongs to the Spring Technology category.@AutowiredPrivateautowirecapablebeanfactory capablebeanfactory; protectedObject createjobinstance (triggerfiredbundle bundle)throwsException {//calling a method of the parent classObject jobinstance =Super. Createjobinstance (bundle); //to inject, this is a spring technology that is not clear to see the Spring API.Capablebeanfactory.autowirebean (jobinstance); returnjobinstance; }}
Package Com.river.service1; Import Org.springframework.stereotype.Service; @Service Public class Testbean {}
Step Three: Add the package scan to be injected in the Spring-job.xml
<context:component-scan base-package = "Com.river.job.listener"/><context:component-scan base- package = "Com.river.service1"/>
You can test it now and the results in the job are as follows:
[Email protected] 2015-09-07 18:41:30
[Email protected]
See here to get the object of Testbean.
Classes used in annotation injection in contextloaderlistener and in jobs using annotation injection