使用spring在Quartz调度程序中完成作业后插入数据

时间:2015-11-24 10:18:37

标签: java spring hibernate spring-mvc quartz-scheduler

我正在处理一项需要在数据库中保存工作状态的任务,但是当我尝试这样做时它会给我java.lang.nullpointerexception。我认为这是因为每当我尝试从数据库中选择/保存/更新任何记录时,它只会给我一个类似的错误。

这是我的代码

public class PostFBJob implements Job {

    private SchedulerService schedulerService;

    private SubCampaignService subCampaignService;

    @SuppressWarnings("unchecked")
    public void execute(JobExecutionContext context) throws JobExecutionException {

        JobDetail jobDetail = context.getJobDetail();
        JobDataMap jobDataMap = jobDetail.getJobDataMap();

        schedulerService = (SchedulerService) jobDataMap.get("schedulerService");

        SubCampaign subCampaign = (SubCampaign) jobDataMap.get("subCampaign");

        if (prStreamItem.getName().equalsIgnoreCase("Facebook") && StringUtils.isNotBlank(branch.getFbAccessToken())) {
            FacebookService facebookService = FacebookService.getSingleton();
            try {
                subCampaign.setStatus("Completed");
                subCampaign.setMessage("Completed");

                subCampaignService.updateSubCampaign(subCampaign);

            } catch (Exception e) {
                log.error("", e);
            }
        }
    }
}

异常

java.lang.NullPointerException
    at com.ace.Job.SubCampaignJob.execute(SubCampaignJob.java:147)
    at org.quartz.core.JobRunShell.run(JobRunShell.java:213)
    at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:557)
Error: java.lang.NullPointerException

请帮我解决这个问题。我是Spring和Quartz的新手。

提前致谢

2 个答案:

答案 0 :(得分:4)

由于subCampaignService的null对象而导致此异常。 注入只能处理由spring管理的对象。

扫描您要使用服务的所有包。

  1. 基于注释的配置

    @ComponentScan({"com.ace"})

  2. 基于XML的配置

    <context:component-scan base-package="com.ace"/>

  3. 并在更新前检查null,如下所示:

    try {
        subCampaign.setStatus("Completed");
        subCampaign.setMessage("Completed");
        if(subCampaign != null && subCampaignService != null) //Check is not null to subCampaign before update
        subCampaignService.updateSubCampaign(subCampaign);
    } catch (Exception e) {
         log.error("", e);
    }
    

答案 1 :(得分:3)

我认为您正在寻找的答案就在这里

请查看以下链接

Correct way to persist Quartz triggers in database

您也可以查看此链接

Using Hibernate session with quartz