第一步、在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中(见下图源码)。

quartz的job怎么获取Spring上下文

第二步:通过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();
        }
    }
}

 

相关文章:

  • 2022-02-27
  • 2022-12-23
  • 2021-11-21
  • 2021-10-26
  • 2022-12-23
  • 2022-02-15
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-01-10
  • 2022-12-23
  • 2021-09-01
  • 2021-09-01
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案