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

本文详细解析了在使用Quartz调度器时遇到的NullPointerException异常,通过分析错误日志,发现异常发生在JobEndConference执行方法中。文章分享了解决方案,即利用SpringContextJobUtil工具类在Job中获取Spring容器中的bean,避免了NullPointerException的发生。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

详细的错误信息如下:

 -- ::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

 

评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值