第一步、在org.springframework.scheduling.quartz.SchedulerFactoryBean对象中注入applicationContextSchedulerContextKey

<bean id="startQuertz" lazy-init="false" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
    <property name="applicationContextSchedulerContextKey" value="applicationContext" />
</bean>

注入applicationContextSchedulerContextKey对象后,SchedulerFactoryBean会将Spring的applicationContext加入到quartz的SchedulerContext中(见下图源码)。

第二步:通过SchedulerContext获取ApplicationContext,下面代码中的applicationContext就是上面applicationContextSchedulerContextKey配置的值。

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.SchedulerContext;
import org.quartz.SchedulerException;
import org.springframework.context.ApplicationContext;

public class TestJob implements Job {

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        try {
            SchedulerContext schedulerContext = context.getScheduler().getContext();
            ApplicationContext applicationContext = (ApplicationContext) schedulerContext.get("applicationContext");

            System.out.println(applicationContext.getId());
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }
}

 

posted on 2019-03-17 22:59  玄同太子  阅读(906)  评论(0编辑  收藏  举报