Spring Boot: Using a @Service in Quartz job execution

前端 未结 2 1140
时光取名叫无心
时光取名叫无心 2021-02-06 01:49

In an application, since I converted it from a classical Spring webapp (deployed in a system Tomcat) to a Spring Boot (V1.2.1) application I face the problem that the Quartz-bas

2条回答
  •  闹比i
    闹比i (楼主)
    2021-02-06 02:08

    The SpringBeanAutowiringSupport uses the web application context, which is not available in your case. If you need a spring managed beans in the quartz you should use the quartz support provided by spring. This will give you full access to all the managed beans. For more info see the quartz section at spring docs at http://docs.spring.io/spring/docs/current/spring-framework-reference/html/scheduling.html. Also see following example of usage quartz with spring managed beans. Example is based on your code. So you can change the first code snippet (where the quartz initialization is done) with follwoing spring alternatives.

    Create job detail factory

    @Component
    public class ScheduledActionRunnerJobDetailFactory extends JobDetailFactoryBean {
    
        @Autowired
        private ScheduleService scheduleService;
    
        @Override
        public void afterPropertiesSet() {
           setJobClass(ScheduledActionRunner.class);
           Map data = new HashMap();
           data.put("scheduleService", scheduleService);
           setJobDataAsMap(data);
           super.afterPropertiesSet();
       }
    }
    

    Create the trigger factory

    @Component
    public class ActionCronTriggerFactoryBean extends CronTriggerFactoryBean {
    
       @Autowired
       private ScheduledActionRunnerJobDetailFactory jobDetailFactory;
    
       @Value("${cron.pattern}")
       private String pattern;
    
       @Override
       public void afterPropertiesSet() throws ParseException {
           setCronExpression(pattern);
           setJobDetail(jobDetailFactory.getObject());
           super.afterPropertiesSet();
       }
    
    }
    

    And finally create the SchedulerFactory

    @Component
    public class ActionSchedulerFactoryBean extends SchedulerFactoryBean {
    
       @Autowired
       private ScheduledActionRunnerJobDetailFactory jobDetailFactory;
    
       @Autowired
       private ActionCronTriggerFactoryBean triggerFactory;
    
       @Override
       public void afterPropertiesSet() throws Exception {
           setJobDetails(jobDetailFactory.getObject());
           setTriggers(triggerFactory.getObject());
           super.afterPropertiesSet();
       }
    
    }
    

提交回复
热议问题