场景:在ContextLoaderListener子类中加载job,为JobFactory的实现类声明@Component后,在ContextLoaderListener子类中为scheduler设置JobFactory。(主要解决的问题:在spring与quartz调用job时,job中无法读取注解类,实现注入)
步骤一:
ContextLoaderListener子类中contextInitialized方法中代码如下:
super.contextInitialized(event); applicationContext = super.getCurrentWebApplicationContext(); scheduler = applicationContext.getBean(Scheduler.class); try { scheduler.setJobFactory(applicationContext.getBean(JobFactory.class)); } catch (BeansException e1) { logger.error(e1.getMessage(),e1); } catch (SchedulerException e1) { logger.error(e1.getMessage(),e1); }
步骤二: 声明JobFactory子类,和job中的服务类
package com.river.job.listener; import org.quartz.spi.TriggerFiredBundle; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.config.AutowireCapableBeanFactory; import org.springframework.scheduling.quartz.AdaptableJobFactory; import org.springframework.stereotype.Component; @Component public class MyJobFactory extends AdaptableJobFactory { // 这个对象Spring会帮我们自动注入进来,也属于Spring技术范畴. @Autowired private AutowireCapableBeanFactory capableBeanFactory; protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception { // 调用父类的方法 Object jobInstance = super.createJobInstance(bundle); // 进行注入,这属于Spring的技术,不清楚的可以查看Spring的API. capableBeanFactory.autowireBean(jobInstance); return jobInstance; } }
package com.river.service1; import org.springframework.stereotype.Service; @Service public class TestBean { }
步骤三:在spring-job.xml中加入要注入的包扫描
<context:component-scan base-package="com.river.job.listener" /> <context:component-scan base-package="com.river.service1" />
现在就可以测试一下,在job中测试结果如下:
river_Worker-2===============com.river.job.HiJobImp@596b2557 2015-09-07 18:41:30
com.river.service1.TestBean@7efd6242
可见这里拿到TestBean的对象了。