- 添加自定义类实现JobFactory接口(参考了org.springframework.scheduling.quartz.AdaptableJobFactory类) - 1 
 2
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 import extensions.InjectorInstance;
 import org.quartz.Job;
 import org.quartz.Scheduler;
 import org.quartz.SchedulerException;
 import org.quartz.spi.JobFactory;
 import org.quartz.spi.TriggerFiredBundle;
 import org.springframework.util.ReflectionUtils;
 import java.lang.reflect.Method;
 /**
 * @author longhuashen
 * @since 2017/9/20
 */
 public class GuiceQuartzAdaptableJobFactory implements JobFactory {
 @Override
 public Job newJob(TriggerFiredBundle triggerFiredBundle, Scheduler scheduler) throws SchedulerException {
 try {
 Object jobObject = createJobInstance(triggerFiredBundle);
 return adaptJob(jobObject);
 }
 catch (Exception ex) {
 throw new SchedulerException("Job instantiation failed", ex);
 }
 }
 protected Job adaptJob(Object jobObject) throws Exception {
 if (jobObject instanceof Job) {
 return (Job) jobObject;
 }
 else {
 throw new IllegalArgumentException("Unable to execute job class [" + jobObject.getClass().getName() +
 "]: only [org.quartz.Job] and [java.lang.Runnable] supported.");
 }
 }
 protected Object createJobInstance(TriggerFiredBundle triggerFiredBundle) throws Exception {
 //调用父类的方法
 Method getJobDetail = triggerFiredBundle.getClass().getMethod("getJobDetail");
 Object jobDetail = ReflectionUtils.invokeMethod(getJobDetail, triggerFiredBundle);
 Method getJobClass = jobDetail.getClass().getMethod("getJobClass");
 Class jobClass = (Class) ReflectionUtils.invokeMethod(getJobClass, jobDetail);
 Object jobInstance = jobClass.newInstance();
 
 //InjectorInstance.injector是获取到Guice Injector对象
 InjectorInstance.injector.injectMembers(jobInstance);
 return jobInstance;
 }
 }
- 注入自定义Factory 
| 1 | @Override | 
- 在自定义Job里注入Guice里的bean1 
 2
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 import com.google.inject.Inject;
 /**
 * @author longhuashen
 * @since 2017/9/20
 */
 public class InventoryWarnJob implements Job {
 @Inject
 private InventoryWarnConfigMapper inventoryWarnConfigMapper;
 }
