問題
我們有時需要執行一些定時任務(如數據批處理),比較常用的技術框架有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。
參考資料
http://stackoverflow.com/questions/6990767/inject-bean-reference-into-a-quartz-job-in-spring