Quartz:ERROR threw an unhandled Exception(Quartz定时任务Job中无法注入spring bean的解决方案)

清疚 2022-12-03 02:27 287阅读 0赞

详细的错误信息如下:

  1. -- ::13.366 [DefaultQuartzScheduler_Worker-] ERROR org.quartz.core.JobRunShell: - Job group1.job1 threw an unhandled Exception:
  2. java.lang.NullPointerException
  3. at com.starunion.java.service.timer.JobEndConference.execute(JobEndConference.java:) ~[bin/:?]
  4. at org.quartz.core.JobRunShell.run(JobRunShell.java:) [quartz-2.2..jar:?]
  5. at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:) [quartz-2.2..jar:?]
  6. -- ::13.374 [DefaultQuartzScheduler_Worker-] ERROR org.quartz.core.ErrorLogger: - Job (group1.job1 threw an exception.
  7. org.quartz.SchedulerException: Job threw an unhandled exception.
  8. at org.quartz.core.JobRunShell.run(JobRunShell.java:) [quartz-2.2..jar:?]
  9. at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:) [quartz-2.2..jar:?]
  10. Caused by: java.lang.NullPointerException
  11. at com.starunion.java.service.timer.JobEndConference.execute(JobEndConference.java:) ~[bin/:?]
  12. at org.quartz.core.JobRunShell.run(JobRunShell.java:) ~[quartz-2.2..jar:?]

说说我的解决过程:

一、原因很明显:调用了null对象。

但是这是因为我调用了service的方法

20200901162433770.png

我用的方法

静态工具类

创建工具类SpringContextJobUtil,实现ApplicationContextAware接口,此工具类会在spring容器启动后,自动加载,使用其提供的getBean方法获取想要的bean即可

  1. @Component
  2. public class SpringContextJobUtil implements ApplicationContextAware {
  3. private static ApplicationContext context;
  4. @Override
  5. @SuppressWarnings("static-access" )
  6. public void setApplicationContext(ApplicationContext contex)
  7. throws BeansException {
  8. // TODO Auto-generated method stub
  9. this.context = contex;
  10. }
  11. public static Object getBean(String beanName){
  12. return context.getBean(beanName);
  13. }
  14. public static String getMessage(String key){
  15. return context.getMessage(key, null, Locale.getDefault());
  16. }
  17. }

在job内直接调用静态方法

  1. testSuitService = (TestSuitService) SpringContextJobUtil.getBean("testSuitService");

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3h0MzE0MTU5_size_16_color_FFFFFF_t_70

参考的网站:

https://www.bbsmax.com/A/obzbYvq6dE/

https://www.jianshu.com/p/aff9199b4416

发表评论

表情:
评论列表 (有 0 条评论,287人围观)

还没有评论,来说两句吧...

相关阅读