spring动态定时器,bean注入为null的问题解决

首先说下具体配置:
pom文件:

        <dependency>
            <groupId>org.quartz-scheduler</groupId>
            <artifactId>quartz</artifactId>
            <version>2.3.0</version>
        </dependency>

spring配置:

    <!--动态定时任务 -->
    <bean id="schedulerFactoryBean"
        class="org.springframework.scheduling.quartz.SchedulerFactoryBean" >
        <property name="jobFactory" ref="myJobFactory"></property>
    </bean>

注意:以上jobFactory这个参数,就是解决问题的地方.重写了这个方法,使得可以注入spring的bean.

//重写方法
@Component(value="myJobFactory")
public class MyJobFactory extends AdaptableJobFactory {

    //这个对象Spring会帮我们自动注入进来,也属于Spring技术范畴.
    @Autowired
    private AutowireCapableBeanFactory capableBeanFactory;

    protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {
        //调用父类的方法
        Object jobInstance = super.createJobInstance(bundle);
        //进行注入,这属于Spring的技术,不清楚的可以查看Spring的API.
        capableBeanFactory.autowireBean(jobInstance);
        return jobInstance;
    }
}

以下是业务处理

//业务处理,并且是依靠spring注入的
@Component
public class EmergenceStartTask implements Job{
    @Autowired
    private EmergencyMapper emergencyMapper;

    private int aqi = 300;
    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        JobDetail jobDetail = context.getJobDetail();
        String uuid = jobDetail.getKey().getName();
        if(aqi>200) {
            emergencyMapper.addAqiCount(uuid);
        }
    }
}

添加定时器任务工具:

    public static void addJob(Scheduler sched, String jobName, @SuppressWarnings("rawtypes") Class cls, String time) {
        try {
            JobKey jobKey = new JobKey(jobName, JOB_GROUP_NAME);// 任务名,任务组,任务执行类
            @SuppressWarnings("unchecked")
            JobDetail jobDetail = newJob(cls).withIdentity(jobKey).build();
            TriggerKey triggerKey = new TriggerKey(jobName, TRIGGER_GROUP_NAME);// 触发器
            Trigger trigger = newTrigger().withIdentity(triggerKey).withSchedule(cronSchedule(time)).build();// 触发器时间设定
            sched.scheduleJob(jobDetail, trigger);
            if (!sched.isShutdown()) {
                sched.start();// 启动
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

这里是业务处理层:

@Service
public class DynamicTaskServiceImpl implements DynamicTaskService {
    private static Logger log = LoggerFactory.getLogger(DynamicTaskServiceImpl.class);
    @Autowired
    private SchedulerFactoryBean SchedulerFactoryBean;

    // 添加预警信息
    @Override
    public boolean addEm(Map<String, Object> paramMap) throws SchedulerException, ClassNotFoundException {
        final String uuid = (String) paramMap.get("uuid");
        final long endTime = (long) paramMap.get("endTime");
        final Scheduler sc = SchedulerFactoryBean.getScheduler();
        String time = Dom4jUtil.get("aqi", "time");
        TaskUtil.addJob(sc, uuid, Class.forName("com.zc.www.task.EmergenceStartTask"), time);
        JobDetail jobDetail = sc.getJobDetail(new JobKey(uuid, "JOB_GROUP_SYSTEM"));

        if (jobDetail != null) {
            log.info("开启定时器成功");
            return true;
        }
        return false;
    }

最关键的地方就是在重写了SchedulerFactoryBean的jobFactory.

阅读更多

没有更多推荐了,返回首页