I am a big Guice advocate. I try to use it wherever it is possible and makes sense. While working on a project yesterday I realized that in order to use Guice and Quartz together you need to add in some glue code.
I found someone who had done the work already but their blog post was from 2009 and the Quartz API had changed a bit. Their implementation was very close so I made the necessary modifications, tested it out, and it works perfectly. If you’re wondering how to use Guice to get dependency injection into your Quartz scheduler code you can use the two snippets of code below to do it all for you.
The first thing you need is a custom job factory that will create your jobs using Guice. Here is the GuiceJobFactory:
importcom.google.inject.Injector;importorg.quartz.Job;importorg.quartz.JobDetail;importorg.quartz.Scheduler;importorg.quartz.SchedulerException;importorg.quartz.spi.JobFactory;importorg.quartz.spi.TriggerFiredBundle;importjavax.inject.Inject;/** * Created by timmattison on 8/4/14. */// Some guidance from: http://codesmell.wordpress.com/2009/01/11/quartz-fits/finalclassGuiceJobFactoryimplementsJobFactory{privatefinalInjectorguice;@InjectpublicGuiceJobFactory(finalInjectorguice){this.guice=guice;}@OverridepublicJobnewJob(TriggerFiredBundletriggerFiredBundle,Schedulerscheduler)throwsSchedulerException{// Get the job detail so we can get the job classJobDetailjobDetail=triggerFiredBundle.getJobDetail();ClassjobClass=jobDetail.getJobClass();try{// Get a new instance of that class from Guice so we can do dependency injectionreturn(Job)guice.getInstance(jobClass);}catch(Exceptione){// Something went wrong. Print out the stack trace here so SLF4J doesn't hide it.e.printStackTrace();// Rethrow the exception as an UnsupportedOperationExceptionthrownewUnsupportedOperationException(e);}}}
The GuiceJobFactory gets the Guice injector injected into it. It then overrides the newJob method and creates each job using the injector it was given.
The next thing you need to do is to use this JobFactory in your Scheduler. Here’s how I built my scheduler and used it to create my first job: