So I have a technical challenge I need help with.
A large scale project is using a Quartz scheduler to schedule a job to run every night at 9.
The Job that is scheduled, however needs to read values from property files, get some beans using auto-wiring etc.
When I used @Autowired and @Value annotations, I found the values to be null.
The issue is that Quartz creates JobDetail objects using newJob() outside the spring container. As can be seen in the below code.
JobKey jobKey = new JobKey("NightJob", "9-PM Job");
JobDetail jobDetail = newJob(NightJob.class).withIdentity(jobKey)
.usingJobData("Job-Id", "1")
.build();
The jobDetail object which wraps NightJob thus cannot access property files or beans using spring.
Here is my NightJob class
public class NightJob implements Job{
//@Value to read from property file; here
//@Autowired to use some beans; here
@Override
public void execute(JobExecutionContext context) throws JobExecutionException{
}
}
I scanned Stack Overflow and shortlisted several solutions. I also read through the comments and listed the top counter-comments.
Suggestion 1: Get rid of Quartz and use Spring Batch due to its good integration with Spring Boot
Counter argument 1: Spring Batch is overkill for simple tasks. Use @Scheduled
Suggestion 2: Use @Scheduled annotations and cron expressions provided by spring
Counter argument 2: Your application will not be future ready if you remove Quartz. Complex scheduling may be required in the future
Suggestion 3 : Use the spring interface ApplicationContextAware.
Counter argument 3: Lots of additional code. Defeats the simple and easy concept of Spring boot
Is there a simpler way in Spring Boot to access property file values and autowire objects in a class that implements a Quartz job (In this situation , the NightJob class)