home personal workZone travel about
code.pst » tech musings and code posts

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!

Tags: ,

2 Responses to “Accessing Spring beans from Quartz jobs”

  1. slim ouertani Says:

    Hi,

    thanks for this post, but why you complicated things so and either to inject context inject directly your dao?

  2. rahul Says:

    Well I’ve learnt more about Spring since last year and Spring 2.5 has OSGi support out of the box. I’ll try and post my updated version soon :)

Leave a Reply