这几天在使用quatz配置定时任务的过程中遇到一个问题,就是spring注入失效,set注入总是为空,代码示例:
package com.ccpit.devplatform.after.weixin;
public class TimingPushTask extends TimerTask {
......
private InfoService infoService;
private NewsService newsService;
public InfoService getInfoService() {
return infoService;
}
public void setInfoService(InfoService infoService) {
this.infoService = infoService;
}
public NewsService getNewsService() {
return newsService;
}
public void setNewsService(NewsService newsService) {
this.newsService = newsService;
}
public List<MessageTempBo> getReadySendInfo(){
log.info("准备获取指定推送资讯......");
String realPath = "E:/apache-tomcat-7.0.59/webapps/txhzWebsite";
// int hour = cal.get(Calendar.HOUR_OF_DAY);
int hour = cal.getTime().getHours();
int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
if(w<0){
w = 0;
}
String str = weekDays[w];
String hql1 = "from InformationInfo where week = '"+ str +"'";
String hql2 = "from NewsInfo where week = '"+ str +"'";
List<InformationInfoBo> listBo = infoService.queryInfosList(hql1);
List<NewsInfoBo> listNBo = newsService.queryNewsInfo(hql2);
......
infoService和newsService 总是null,经过多次尝试问题解决,需要在applicationContext.xml中配置:
<!-- 配置定时执行方法 -->
<bean id="jobBean" class="com.ccpit.devplatform.after.weixin.TimingPushTask">
<property name="infoService" ref="infoService"></property>
<property name="newsService" ref="newsService"></property>
</bean>
<bean id="jobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<property name="targetObject" ref="jobBean" />
<property name="targetMethod" value="previewMsg" />
<!--将并发设置为false -->
<property name="concurrent" value="false" />
</bean>
<bean id="trigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
<property name="jobDetail" ref="jobDetail" />
<!--配置每 10分钟 执行一次 -->
<property name="cronExpression" value="0 0/10 * * * ?" />
</bean>
<!-- 总管理类如果将lazy-init='false'那么容器启动就会执行调度程序 -->
<bean id="startQuertz" class="org.springframework.scheduling.quartz.SchedulerFactoryBean"
lazy-init="false">
<property name="triggers">
<list>
<!--作业调度器,list下可加入其他的调度器 -->
<ref bean="trigger" />
</list>
</property>
</bean>