quartz的job怎么获取Spring上下文

第一步、在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();
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/zhi-leaf/p/10549582.html