Spring Boot中使用Quartz, 在Job中沒法注入其餘Bean

使用Quartz來按期發送告警任務,告警Job如:html

public class AlarmJob implements Job {
    @Resource
    private StoreRepository storeRepository;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
       // 告警邏輯
    }
}

StoreRepository是Spring Boot中的bean,該Job被觸發後,始終得不到該bean的實例,參考了https://blog.csdn.net/xiaobuding007/article/details/80455187java

配置一個JobFactoryspring

@Component
public class JobFactory extends AdaptableJobFactory {
    /**
     * AutowireCapableBeanFactory接口是BeanFactory的子類
     * 能夠鏈接和填充那些生命週期不被Spring管理的已存在的bean實例
     */
    private AutowireCapableBeanFactory factory;

    public JobFactory(AutowireCapableBeanFactory factory) {
        this.factory = factory;
    }

    /**
     * 建立Job實例
     */
    @Override
    protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {

        // 實例化對象
        Object job = super.createJobInstance(bundle);
        // 進行注入(Spring管理該Bean)
        factory.autowireBean(job);
        //返回對象
        return job;
    }
}

並將該JobFactory配置到less

@Configuration
@Slf4j
public class SchedulerConfig {

    private JobFactory jobFactory;

    public SchedulerConfig(JobFactory jobFactory){
        this.jobFactory = jobFactory;
    }

    @Bean(name="SchedulerFactory")
    public SchedulerFactoryBean schedulerFactoryBean() throws IOException {
        SchedulerFactoryBean factory = new SchedulerFactoryBean();
        factory.setQuartzProperties(quartzProperties());
        factory.setJobFactory(jobFactory);
        return factory;
    }

    @Bean
    public Properties quartzProperties() throws IOException {
        PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
        propertiesFactoryBean.setLocation(new ClassPathResource("/quartz.properties"));
        //在quartz.properties中的屬性被讀取並注入後再初始化對象
        propertiesFactoryBean.afterPropertiesSet();
        return propertiesFactoryBean.getObject();
    }

    /*
     * quartz初始化監聽器
     */
    @Bean
    public QuartzInitializerListener executorListener() {
        return new QuartzInitializerListener();
    }

    /*
     * 經過SchedulerFactoryBean獲取Scheduler的實例
     */
    @Bean(name="Scheduler")
    public Scheduler scheduler() throws IOException {
         return schedulerFactoryBean().getScheduler();
    }

}

配置完JobFactory以後,注入的問題獲得解決。一開始我覺得是Quartz沒作好,看了一下官方的tutorial,原來人家原本沒打算自動支持Spring Boot的DI。ide

官方tutorial:spring-boot

http://www.quartz-scheduler.org/documentation/2.4.0-SNAPSHOT/tutorials/tutorial-lesson-12.htmlthis

 

相關文章
相關標籤/搜索