NullPointerException while deploying Quartz in Spring Boot

前端 未结 2 1468
说谎
说谎 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 05:47

    Spring Boot manages it for you. Remove the quartz dependency and just create a Service for having scheduled executions:

    @Service
    public class JobScheduler{
    
        @Autowired
        JobController controller;
    
        //Executes each 5000 ms
        @Scheduled(fixedRate=5000)
        public void performJob() {
            controller.doPrintData();
        }
    }
    

    And enable the task scheduling for your application:

    @SpringBootApplication
    @EnableScheduling
    public class Application {
    
        public static void main(String[] args) throws Exception {
            SpringApplication.run(Application.class);
        }
    }
    

    See also:

    • Scheduling Tasks in Spring Boot
    0 讨论(0)
  • 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);
    
    0 讨论(0)
提交回复
热议问题