Sunday, March 11, 2007

Accessing Spring beans from Quartz jobs

I had referred to Mark’s blog in my earlier post and actually now have a improvement over his solution. Define your context as usual (courtesy to Mark for his example)
<beans>
  <!-- Define the Job Bean that will be executed. 
  Our bean is named in the jobClass property. -->
  <bean name="myJob" class="org.springframework.scheduling.quartz.JobDetailBean">
    <property name="jobClass" value="com.gsoftware.common.util.MyJob"/>
  </bean>
  <!-- Associate the Job Bean with a Trigger. 
  Triggers define when a job is executed. -->
  <bean id="simpleTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerBean">
    <!-- see the example of method invoking job above -->
    <property name="jobDetail" ref="myJob"/>
    <property name="startDelay" value="2000"/>
    <property name="repeatInterval" value="10000"/>
  </bean>
  <!-- A list of Triggers to be scheduled and executed by Quartz -->
  <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
    <property name="triggers">
      <list><ref bean="simpleTrigger"/></list>
    </property>
    <property name="applicationContextSchedulerContextKey" value="applicationContext"/>
  </bean>
</beans>
Note that in the factory I have added the property for the application context.
Now all you need to do in your job is extend the spring base class QuartzJobBean for a job and create a setter as follows:
public class MyJob extends QuartzJobBean {
  private ApplicationContext applicationContext;
 
  public void setApplicationContext(ApplicationContext appContext) {
    applicationContext = appContext;
  }
 
  @Override
  protected void executeInternal(JobExecutionContext executionContext) {
    //your code...
 
  }
}
Now you have the application context available in your job. Nothing else required!

No comments: