解決Spring+Quartz無法自動注入bean問題


問題

我們有時需要執行一些定時任務(如數據批處理),比較常用的技術框架有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。

解決方法

    1. 成員變量添加注解@Autowired

    2. 然后在方法中(如例子中的queryTraderNo方法)添加以下代碼,自動注入成員變量實現類

      SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);

       

       

 

關於引發這個問題的原因,有待深入驗證。說的比較多的是Quartz與SpringMVC的context不同,父context無法訪問子context中的bean。

參考資料

http://stackoverflow.com/questions/6990767/inject-bean-reference-into-a-quartz-job-in-spring


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM