java – Spring cannot inject Bean in class that implements Quartz Job

java – Spring cannot inject Bean in class that implements Quartz Job

You will want to use the spring helpers/implementations of the various Quartz components, so that the jobs you create will be managed by spring.

… are two good starting points (although youll want to make sure the documentation you look at is appropriate for the version of spring youre using; spring-boot for example has a starter for scheduling/quartz)

Did you add AutowiringSpringBeanJobFactory in your project? This will add the support of autowiring to quartz jobs.

public final class AutowiringSpringBeanJobFactory extends SpringBeanJobFactory implements ApplicationContextAware {

    private transient AutowireCapableBeanFactory beanFactory;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        beanFactory = applicationContext.getAutowireCapableBeanFactory();        
    }

    @Override
    protected Object createJobInstance(final TriggerFiredBundle bundle) throws Exception {
        final Object job = super.createJobInstance(bundle);
        beanFactory.autowireBean(job);
        return job;
    }
}

You also need to create a jobFactory and set the application context to your quartz jobs. This should be in a @Configuration class

 @Bean
 public JobFactory jobFactory(ApplicationContext applicationContext)
 {
     AutowiringSpringBeanJobFactory jobFactory = new AutowiringSpringBeanJobFactory();
     jobFactory.setApplicationContext(applicationContext);
     return jobFactory;
 }

(Just copy and paste this class in your project)

java – Spring cannot inject Bean in class that implements Quartz Job

Leave a Reply

Your email address will not be published. Required fields are marked *