请问如何在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>
在声明Scheduler时,放入JobDataMap中,在Job中通过JobExecutionContext获取.