NullPointerException while deploying Quartz in Spring Boot

前端 未结 2 1485
说谎
说谎 2020-12-12 05:43

I am trying to use Quartz 2.2.1 with spring boot. Im trying to declare a scheduled task that is supposed to write some datas into a file. My Job is defined like below :

2条回答
  •  孤街浪徒
    2020-12-12 06:02

    You need to use SpringBeanJobFactory to create Job with Spring's autowired beans.

    class AutowiringSpringBeanJobFactory extends SpringBeanJobFactory implements ApplicationContextAware {
        private transient AutowireCapableBeanFactory beanFactory;
    
        public void setApplicationContext(final ApplicationContext context) {
            beanFactory = context.getAutowireCapableBeanFactory();
        }
    
        @Override
        public Object createJobInstance(final TriggerFiredBundle bundle) throws Exception {
           final Object job = super.createJobInstance(bundle);
           beanFactory.autowireBean(job);  //the magic is done here
           return job;
        }
    }
    

    And then when you do

        SchedulerFactory schedFact = new org.quartz.impl.StdSchedulerFactory();
        scheduler = schedFact.getScheduler();
    
        AutowiringSpringBeanJobFactory autowiringSpringBeanJobFactory = new AutowiringSpringBeanJobFactory();
        autowiringSpringBeanJobFactory.setApplicationContext(applicationContext);
        scheduler.setJobFactory(autowiringSpringBeanJobFactory);
    

提交回复
热议问题