如何在Quartz的Job类中获取到Service?

请问如何在Quartz的Job类中获取到Service,在Job类中获取Service都是Null。
网上找了几种方法也没有解决,代码在下面,请各位帮忙看看。

报错信息

java.lang.NullPointerException
    at com.wufu.util.SpringContextUtil.getBean(SpringContextUtil.java:26)
    at com.xinfu.quartz.QuartzJob.execute(QuartzJob.java:27)
    at org.quartz.core.JobRunShell.run(JobRunShell.java:202)
    at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:573)

声明定时任务

   long time = System.currentTimeMillis()+2000;
            SchedulerFactory sf = new StdSchedulerFactory();
            Scheduler sched = sf.getScheduler();
            Date runTime = DateBuilder.evenSecondDate(timestampToDate(time));
            JobDetail job = JobBuilder.newJob(QuartzJob.class)
                    .withIdentity("job1", "group1")
                    .usingJobData("param", 389)
                    .build();
            Trigger trigger = TriggerBuilder.newTrigger()
                    .withIdentity("trigger1", "group1")
                    .startAt(runTime)
                    .build();

Job类

public class QuartzJob implements Job {
    @Override
    public void execute(JobExecutionContext content) throws JobExecutionException {
        try {
            RefundService rs = (RefundService)SpringContextUtil.getBean("RefundService");
            System.out.println(rs.refund());
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

获取Bean工具类

@Component
public class SpringContextUtil implements ApplicationContextAware {
    private static ApplicationContext context;

    @Override
    @SuppressWarnings("static-access" )
    public void setApplicationContext(ApplicationContext contex) throws BeansException {
        this.context = contex;
    }
    public static Object getBean(String beanName){
        return context.getBean(beanName);
    }
    public static String getMessage(String key){
        return context.getMessage(key, null, Locale.getDefault());
    }
    public static Object getBeanByClass(Class elementType) {
        return context.getBean(elementType);
    }
}

ApplicationContext.xml

 <bean id="SpringContextUtil" class="com.XXX.util.SpringContextUtil"  lazy-init="false"></bean>
<bean id="RefundService" class="com.XXX.serv.RefundService"  ></bean>
<bean id="QuartzJob" class="com.XXX.quartz.QuartzJob"></bean>
阅读 3.9k
3 个回答

在声明Scheduler时,放入JobDataMap中,在Job中通过JobExecutionContext获取.

题主的获取方式没问题,没有获取到那就是获取的时机不对,也就是在获取RefundService的时候,RefundService这个bean还没有被加载到Spring的IOC中,可以把Job的执行时间设置大些来验证是不是这个原因。如果是可以通过调整Quartz和bean的加载顺序来解决问题

@Component
public class NewJob implements Job {
    @Resource
    private HelloService helloService;
}

我这样做没问题。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题