我们有时需要执行一些定时任务(如数据批处理),比较常用的技术框架有Spring + Quartz中。无奈此方式有个问题:Spring Bean无法自动注入。
环境:Spring3.2.2 + Quartz1.6.1
Quartz配置:
<bean id="traderRiskReportJob" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"> <property name="targetObject" ref="traderNoServerResource" /> <property name="targetMethod" value="queryTraderNo" /> <property name="concurrent" value="true" /> </bean>
service配置:
<bean name="traderNoServerResource" class="com.test.TraderNoServerResource" > <property name="threadPool" ref="threadPool"/> </bean>
ThreadPool配置:
<bean name="threadPool" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor" > <property name="corePoolSize" value="25"></property> <property name="maxPoolSize" value="100"></property> </bean>
出现的问题是:traderNoServerResource中的threadPool为null。
解决方法
-
成员变量添加注解@Autowired
-
然后在方法中(如例子中的queryTraderNo方法)添加以下代码,自动注入成员变量实现类
SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
-
关于引发这个问题的原因,有待深入验证。说的比较多的是Quartz与SpringMVC的context不同,父context无法访问子context中的bean。
本文介绍在Spring和Quartz结合使用时遇到的Bean自动注入问题及解决方案。通过在成员变量上添加@Autowired注解,并在定时任务方法中调用SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this),实现自动注入。
1925

被折叠的 条评论
为什么被折叠?



