Quartz:ERROR threw an unhandled Exception(Quartz定时任务Job中无法注入spring bean的解决方案)
详细的错误信息如下:
-- ::13.366 [DefaultQuartzScheduler_Worker-] ERROR org.quartz.core.JobRunShell: - Job group1.job1 threw an unhandled Exception:
java.lang.NullPointerException
at com.starunion.java.service.timer.JobEndConference.execute(JobEndConference.java:) ~[bin/:?]
at org.quartz.core.JobRunShell.run(JobRunShell.java:) [quartz-2.2..jar:?]
at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:) [quartz-2.2..jar:?]
-- ::13.374 [DefaultQuartzScheduler_Worker-] ERROR org.quartz.core.ErrorLogger: - Job (group1.job1 threw an exception.
org.quartz.SchedulerException: Job threw an unhandled exception.
at org.quartz.core.JobRunShell.run(JobRunShell.java:) [quartz-2.2..jar:?]
at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:) [quartz-2.2..jar:?]
Caused by: java.lang.NullPointerException
at com.starunion.java.service.timer.JobEndConference.execute(JobEndConference.java:) ~[bin/:?]
at org.quartz.core.JobRunShell.run(JobRunShell.java:) ~[quartz-2.2..jar:?]
说说我的解决过程:
一、原因很明显:调用了null对象。
但是这是因为我调用了service的方法
我用的方法
静态工具类
创建工具类SpringContextJobUtil
,实现ApplicationContextAware
接口,此工具类会在spring容器启动后,自动加载,使用其提供的getBean
方法获取想要的bean即可
@Component
public class SpringContextJobUtil implements ApplicationContextAware {
private static ApplicationContext context;
@Override
@SuppressWarnings("static-access" )
public void setApplicationContext(ApplicationContext contex)
throws BeansException {
// TODO Auto-generated method stub
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());
}
}
在job内直接调用静态方法
testSuitService = (TestSuitService) SpringContextJobUtil.getBean("testSuitService");
参考的网站:
https://www.bbsmax.com/A/obzbYvq6dE/
https://www.jianshu.com/p/aff9199b4416
还没有评论,来说两句吧...