Can't inject dependencies in Quartz jobs

Viewed 127

I'm trying to inject dependencies into Quartz jobs, but whenever my job is triggered, i have a NullPointerException on my injected service.

I followed several tutorials/blogs on how to solve that issue, but it's remaining.

Note that i'll be creating several Jobs within the first job depending on some business logic. /!\ : While the debugging : JobExecutionContext.getScheduler().getContext().get("applicationContext") is null Everything regarding creating the jobs and triggers (even CRONs) is good. the only problem is i'm Always having NPE on the "campagneService".

My Job:

@Component
@DisallowConcurrentExecution
public class CreateAndCheckFirstCommandeJob implements Job {
            
            @Autowired
            private CampagneService campagneService;

            @Override
            public void execute(JobExecutionContext context) throws JobExecutionException {
               *** buisiness Logic ****
Scheduler scheduler = new StdSchedulerFactory().getScheduler();
    scheduler.start();
JobDetail jobDetail= QuartzConfig.createQuartzJobDetail(a,b,c );

    Trigger trigger= QuartzConfig.createQuartzSimpleTrigger(x, y, z ,t);
    
    scheduler.scheduleJob(jobDetail, trigger);
}
}

Configuration :

@Configuration
public class QuartzConfig {
    
    private ApplicationContext applicationContext;
    
   
    public QuartzConfig(ApplicationContext applicationContext, DataSource dataSource) {
        this.applicationContext = applicationContext;
        this.dataSource = dataSource;
    }
    
    @Bean
    public SpringBeanJobFactory springBeanJobFactory() {
        AutowiringSpringBeanJobFactory jobFactory = new AutowiringSpringBeanJobFactory();
        jobFactory.setApplicationContext(applicationContext);
        return jobFactory;
    }
    
    @Bean
    public SchedulerFactoryBean scheduler(Trigger... triggers) {
        SchedulerFactoryBean schedulerFactory = new SchedulerFactoryBean();
        Properties properties = new Properties();
        properties.setProperty("org.quartz.scheduler.instanceName", "SCHEDULER");
        properties.setProperty("org.quartz.scheduler.instanceId", "Scheduler-1");
        schedulerFactory.setOverwriteExistingJobs(true);
        schedulerFactory.setAutoStartup(true);
        schedulerFactory.setQuartzProperties(properties);
        schedulerFactory.setDataSource(dataSource);
        schedulerFactory.setJobFactory(springBeanJobFactory());
        schedulerFactory.setWaitForJobsToCompleteOnShutdown(true);
        if (ArrayUtils.isNotEmpty(triggers)) {
            schedulerFactory.setTriggers(triggers);
        }
        return schedulerFactory;
    }

static JobDetail createQuartzJobDetail(Class jobClazz, String jobGroup, Map<String, Object> jobDataMap) {
    String jobName = jobClazz.getSimpleName()
    JobKey jobUniqueKey = new JobKey(jobName, jobGroup);
    JobDetail jobDetail = JobBuilder.newJob(jobClazz)
                        .withIdentity(jobUniqueKey).build();
    

    return jobDetail;
}

static Trigger createQuartzSimpleTrigger(JobDetail jobDetail,String triggerName, String triggerGroup, Date startingDate) {

    return TriggerBuilder.newTrigger()
            .withIdentity(triggerName , triggerGroup).forJob(jobDetail)
            .startAt(startingDate) 
            .build();
}

static Trigger createQuartzCronTrigger(JobDetail jobDetail, String triggerName, String triggerGroup, Date endDate, String cronExpression) {
    return TriggerBuilder.newTrigger()
            .withIdentity( triggerName, triggerGroup)
            .withSchedule(
                    CronScheduleBuilder.cronSchedule(cronExpression))
            .endAt(endDate).forJob(jobDetail)
            .build();
}
}

AutowiringSpringJobFactory:

public final class AutowiringSpringBeanJobFactory extends SpringBeanJobFactory implements ApplicationContextAware {

    private AutowireCapableBeanFactory beanFactory;
    


    @Override
    public void setApplicationContext(final ApplicationContext ctx) {
        beanFactory = ctx.getAutowireCapableBeanFactory();
        
    }

    @Override
    protected Object createJobInstance(final TriggerFiredBundle bundle) throws Exception {
        final Object job = super.createJobInstance(bundle);
        beanFactory.autowireBean(job);
        return job; 
    }
   
}

the stack strace (in case of :D ) the line 71 is where i call my service (this.campagneService.xxx)

2020-08-31 15:56:24.647 ERROR 8056 --- [eduler_Worker-1] org.quartz.core.JobRunShell              : Job Cammande.CreateAndCheckPremiereCommandeJob15:56:14.434 threw an unhandled Exception:
    
    java.lang.NullPointerException: null
            at com.gtmt.scheduler.quartz.config.CreateAndCheckFirstCommandeJob.execute(CreateAndCheckFirstCommandeJob.java:71)
            at org.quartz.core.JobRunShell.run(JobRunShell.java:202)
            at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:573)
    
    2020-08-31 15:56:24.650 ERROR 8056 --- [eduler_Worker-1] org.quartz.core.ErrorLogger              : Job (Cammande.CreateAndCheckFirstCommandeJob15:56:14.434 threw an exception.
    
    org.quartz.SchedulerException: Job threw an unhandled exception.
            at org.quartz.core.JobRunShell.run(JobRunShell.java:213)
            at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:573)
    Caused by: java.lang.NullPointerException: null
            at com.gtmt.scheduler.quartz.config.CreateAndCheckFirstCommandeJob.execute(CreateAndCheckFirstCommandeJob.java:71)
            at org.quartz.core.JobRunShell.run(JobRunShell.java:202)
            ... 1 common frames omitted
    
   


Thanks.
0 Answers
Related