I would like Guice to inject into implementations of Quartz's Job
interface, so that the jobs have access to the injected members.
Does anyone have any code samples for doing this, or any pointers? I'm
quite new to Quartz, so I don't know whether there is something to
extend in order to get Guice to do the injection...
Perhaps there is a beforeExecute() method that I can override
somewhere?
Thanks in advance
Rich
I've only used Quartz once, and just for trivial things, but by
looking a bit at the API you can find the org.quartz.spi.JobFactory
interface.
You can create a custom JobFactory, provide it a reference of the
injector and then inject dependencies on the newly created Job object:
public class GuiceJobFactory implements JobFactory {
private final Injector injector;
public GuiceJobFactory(Injector inj) {
injector = inj;
}
public Job newJob(TriggerFiredBundle triggerFiredBundle) throws
SchedulerException {
Job job = null;
try {
job= (Job)
triggerFiredBundle.getJobDetail().getJobClass().newInstance();
} catch (Exception ex) {
throw new SchedulerException(ex);
}
injector.injectMembers(job);
return job;
}
You can then provide a new JobFactory to your scheduler through a
Provider:
public class SchedulerProvider implements Provider<Scheduler> {
@Inject Injector injector;
public Scheduler get() {
try {
org.quartz.impl.StdSchedulerFactory factory = new
org.quartz.impl.StdSchedulerFactory();
org.quartz.Scheduler scheduler = factory.getScheduler();
scheduler.setJobFactory(new GuiceJobFactory(injector));
return scheduler;
}
catch (SchedulerException ex) {
...
}
}
}
Finally, you can configure the Scheduler through a Module:
bind(Scheduler.class).toProvider(SchedulerProvider.class).asEagerSingleton();
I used "asEagerSingleton" to force the instanciation and configuration
of the Scheduler at deployment, and get all the possible configuration
errors as soon as possible.
I haven't actually used this method (I haven't used Guice for anything
yet! :D ) but a small experiment I did seems to work. I hope that
makes sense to you.
Let me know if I am diverging form Guice or Quartz filosophy.
Christophoros