inject bean reference into a Quartz job in Spring?
You can use this SpringBeanJobFactory
to automatically autowire quartz objects using spring:
import org.quartz.spi.TriggerFiredBundle;import org.springframework.beans.factory.config.AutowireCapableBeanFactory;import org.springframework.context.ApplicationContext;import org.springframework.context.ApplicationContextAware;import org.springframework.scheduling.quartz.SpringBeanJobFactory;public final class AutowiringSpringBeanJobFactory extends SpringBeanJobFactory implements ApplicationContextAware { private transient AutowireCapableBeanFactory beanFactory; @Override public void setApplicationContext(final ApplicationContext context) { beanFactory = context.getAutowireCapableBeanFactory(); } @Override protected Object createJobInstance(final TriggerFiredBundle bundle) throws Exception { final Object job = super.createJobInstance(bundle); beanFactory.autowireBean(job); return job; }}
Then, attach it to your SchedulerBean
(in this case, with Java-config):
@Beanpublic SchedulerFactoryBean quartzScheduler() { SchedulerFactoryBean quartzScheduler = new SchedulerFactoryBean(); ... AutowiringSpringBeanJobFactory jobFactory = new AutowiringSpringBeanJobFactory(); jobFactory.setApplicationContext(applicationContext); quartzScheduler.setJobFactory(jobFactory); ... return quartzScheduler;}
Working for me, using spring-3.2.1 and quartz-2.1.6.
Check out the complete gist here.
I found the solution in this blog post
I just put SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
as first line of my Job.execute(JobExecutionContext context)
method.
Same problem has been resolved in LINK:
I could found other option from post on the Spring forum that you can pass a reference to the Spring application context via the SchedulerFactoryBean. Like the example shown below:
<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean"><propertyy name="triggers"> <list> <ref bean="simpleTrigger"/> </list> </property> <property name="applicationContextSchedulerContextKey"> <value>applicationContext</value></property>
Then using below code in your job class you can get the applicationContext and get whatever bean you want.
appCtx = (ApplicationContext)context.getScheduler().getContext().get("applicationContextSchedulerContextKey");
Hope it helps.You can get more information from Mark Mclaren'sBlog