Spring使用Quartz定時排程Job無法Autowired注入Service的解決方案
專案過程中有這樣一個場景:呼叫微信開放平臺介面獲取access_token,每2小時access_token失效一次,每天限額2000次,因此在專案中做了如下處理:
1)啟動服務時,呼叫外部介面獲取access_token入庫;
2)每隔1小時呼叫一次外部介面,獲取最新的access_token入庫;
針對上述第1)點,直接使用mvc的方式,在service層呼叫外部介面即可,這裡需要使用到幾個引數:grant_type,appid,secret,這些引數在配置檔案中通過@Vaue的方式注入進來,在Controller呼叫Service時可以使用,那麼問題來了:
第2)點,在定時呼叫時,也希望通過注入的Service直接使用呼叫方法,寫法如下:
@Component
public class AccessTokenJob extends QuartzJobBean{
@Autowired
private AccessTokenService accessTokenService;
@Override
protected void executeInternal(JobExecutionContext arg0) throws JobExecutionException
{
this.accessTokenService.processAccessToken();
}
}
這裡的accessTokenService竟然無法注入,直接導致使用時產生空指標異常!
上網找了一些方法,大都不管用,最終解決辦法如下:
1)自定義JobFactory,通過spring的AutowireCapableBeanFactory進行注入,例如:
public class MyJobFactory extends org.springframework.scheduling.quartz.SpringBeanJobFactory
{
@Autowired
private AutowireCapableBeanFactory beanFactory;
/**
* 這裡覆蓋了super的createJobInstance方法,對其創建出來的類再進行autowire。
*/
@Override
protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {
Object jobInstance = super.createJobInstance(bundle);
beanFactory.autowireBean(jobInstance);
return jobInstance;
}
}
2)定義上述類之後,需要在定義觸發器,引用org.springframework.scheduling.quartz.SpringBeanJobFactory的地方,配置property,例如(見紅色部分):
<bean name="quartzScheduler" lazy-init="false"
class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="dataSource" ref="ds" />
<property name="applicationContextSchedulerContextKey" value="applicationContextKey" />
<property name="configLocation" value="classpath:quartz.properties" />
<property name="triggers">
<list>
<ref bean="trigger" />
</list>
</property>
<property name="jobFactory">
<bean class="com.xxx.MyJobFactory" />
</property>
</bean>如此,大功告成!