Quartz Job 中无法注入 Service

一、原因

Job 是在 quartz 的框架中实例化的,service 是在 spring 容器中创建出来的,所以 Job 实现类不受 spring 管理,即导致注入失败。

二、解决方法

1、描述

将 Job 交给 Spring 管理。

2、步骤

1. 创建 AdaptableJobFactory 的子类,并重写 createJobInstance 方法。
public class JobFactory extends AdaptableJobFactory {

    @Autowired
    private AutowireCapableBeanFactory capableBeanFactory;

    @Override
    protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {
        // 调用父类的方法
        Object jobInstance = super.createJobInstance(bundle);
        // 进行注入
        capableBeanFactory.autowireBean(jobInstance);
        return jobInstance;
    }
}
2.从 SchedulerFactoryBean 中获取 Scheduler。
2.1 SpringContextUtil
public class SpringContextUtil implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    /**
     * 实现ApplicationContextAware接口的回调方法,设置上下文环境
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        SpringContextUtil.applicationContext = applicationContext;
    }

    /**
     * 加载spring配置文件
     */
    public static ApplicationContext getApplicationContext() {
        if(applicationContext == null) {
            applicationContext = ContextLoader.getCurrentWebApplicationContext();
        }
        if(applicationContext == null) {
            applicationContext = new ClassPathXmlApplicationContext("spring-config.xml");
        }
        return applicationContext;
    }

    /**
     * 获取对象
     */
    public static Object getBean(String name) throws BeansException {
        return applicationContext.getBean(name);
    }
}
2.2 Spring 配置文件
<bean id="jobFactory" class="com.wangzhixuan.task.JobFactory"/>
<bean id="schedulerFactoryBean" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
    <property name="jobFactory" ref="jobFactory"/>
</bean>
<bean id="springContextUtil" class="com.wangzhixuan.util.SpringContextUtil" lazy-init="false"/>
<bean id="quartzSchedule" class="com.wangzhixuan.task.QuartzSchedule" init-method="startDataImportTask"/>
2.3 Scheduler 调度器从 SpringContextUtil 中获取
@PropertySource("classpath:quartz.properties")
@Component
public class QuartzSchedule {

    @Value("${cron.hisDataSourceImportCron}")
    private String hisDataSourceImportCron;
    @Value("${cron.platformDataSourceImportCron}")
    private String platformDataSourceImportCron;
    public static final String HIS_DATA_SOURCE = "HIS数据源";
    public static final String PLATFORM_DATA_SOURCE = "平台数据源";
    private static Scheduler scheduler = (Scheduler) SpringContextUtil.getApplicationContext()
            .getBean("schedulerFactoryBean");

    @Autowired
    private IDataImportSourceService dataImportSourceService;

    public void startDataImportTask() throws SchedulerException {
        DataImportSource importSource = dataImportSourceService.getEnabledOne();
        if (importSource != null) {
            if (HIS_DATA_SOURCE.equals(importSource.getDataImportSource())) {
                addHisDataSourceImportTask();
            } else if (PLATFORM_DATA_SOURCE.equals(importSource.getDataImportSource())) {
                addPlatformDataSourceImportTask();
            }
        } else {
            addHisDataSourceImportTask();
        }
    }

    public void addHisDataSourceImportTask() throws SchedulerException {
        JobDetail hisJobDetail = JobBuilder.newJob(HisDataSourceImport.class)
                .withIdentity("HISJob", "HIS")
                .build();
        CronTrigger trigger = TriggerBuilder.newTrigger()
                .withIdentity("HISTrigger", "HIS")
                // .startNow()
                .withSchedule(CronScheduleBuilder.cronSchedule(hisDataSourceImportCron))
                .build();
        scheduler.scheduleJob(hisJobDetail, trigger);
        scheduler.start();
    }

    private void addPlatformDataSourceImportTask() throws SchedulerException {
        JobDetail platformJobDetail = JobBuilder.newJob(PlatformDataSourceImport.class)
                .withIdentity("PlatformJob", "Platform")
                .build();
        CronTrigger trigger = TriggerBuilder.newTrigger()
                .withIdentity("PlatformTrigger", "Platform")
                .startNow()
                .withSchedule(CronScheduleBuilder.cronSchedule(platformDataSourceImportCron))
                .build();
        scheduler.scheduleJob(platformJobDetail, trigger);
        scheduler.start();
    }

    public void toggleToPlatformDataSourceImportTask() throws SchedulerException {
        if (scheduler.checkExists(JobKey.jobKey("HISJob", "HIS"))) {
            scheduler.pauseJob(JobKey.jobKey("HISJob", "HIS"));
        }
        if (scheduler.checkExists(JobKey.jobKey("PlatformJob", "Platform"))) {
            scheduler.resumeJob(JobKey.jobKey("PlatformJob", "Platform"));
        } else {
            addPlatformDataSourceImportTask();
        }
    }

    public void toggleToHisDataSourceImportTask() throws SchedulerException {
        if (scheduler.checkExists(JobKey.jobKey("PlatformJob", "Platform"))) {
            scheduler.pauseJob(JobKey.jobKey("PlatformJob", "Platform"));
        }
        if (scheduler.checkExists(JobKey.jobKey("HISJob", "HIS"))) {
            scheduler.resumeJob(JobKey.jobKey("HISJob", "HIS"));
        } else {
            addHisDataSourceImportTask();
        }
    }
}
2.4 Quartz Job
@Component
public class HisDataSourceImport implements Job {

    @Autowired
    private FangAnPiPeiTask fangAnPiPeiTask;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) {
        fangAnPiPeiTask.cronTest();
    }
}
@Component
public class PlatformDataSourceImport implements Job {

    @Autowired
    private FangAnPiPeiTask fangAnPiPeiTask;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) {
        fangAnPiPeiTask.exeTask(new Task());
    }
}

你可能感兴趣的:(Quartz)