Spring的自动任务中调用业务类方法
Spring 中使用 QuartzJobBean 来进行定时任务的操作
代码如下:
@Controller @Scope("prototype")
public class QuartzSyncJob extends QuartzJobBean {
private MsgBusinessImpl msgBusinessImpl ;
public void setMsgBusinessImpl(MsgBusinessImpl msgBusinessImpl) {
this.msgBusinessImpl = msgBusinessImpl;
}
protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
if(msgBusinessImpl != null){
msgBusinessImpl.deleteMsg(1);
}
}
}
其中private MsgBusinessImpl msgBusinessImpl ; 和setMsgBusinessImpl 这两个步十分重要,本来也想用action中那种方案自动注入,调用实例的,结果总是空指针。
用此方案,还需要在Spring配置文件,加入 <ref bean="msgBusinessImpl"/>
这样,自动任务中的业务类,就能得到0实例了。
<!-- Configure the sync Service -->
<bean name="randomSyncJob"
class="org.springframework.scheduling.quartz.JobDetailBean">
<property name="jobClass">
<value>com.fireinwind.job.QuartzSyncJob</value>
</property>
<property name="jobDataAsMap">
<map>
<entry key="timeout">
<value>5</value>
</entry>
<entry key="msgBusinessImpl">
<ref bean="msgBusinessImpl"/>
</entry>
</map>
</property>
</bean>
<!-- 配置触发器 -->
<bean id="cronTrigger"
class="org.springframework.scheduling.quartz.CronTriggerBean">
<property name="jobDetail">
<ref bean="randomSyncJob" />
</property>
<!-- 每天0点0分,触发RandomPriceJob,具体说明见附录 -->
<property name="cronExpression">
<value>0 0 0 * * ?</value>
</property>
</bean>
<bean autowire="no"
class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<!-- 添加触发器 -->
<property name="triggers">
<list>
<ref local="cronTrigger" />
</list>
</property>
</bean>
==========
自己在另一个项目(tdstatistic)中也想用此算法,ShopBusiness是接口,怎么折腾也没折腾成功,后来又定义了一个ShopBusiness2为真实的业务类才解决接口类注入失败的问题,早知道自己是这么写的,把实现类注入不就行了。呵。。。。
2012-11-18晚
------------------------------------------------------
2013-07-18 总结
在配置文件中的类不是接口
应该是这个样子的
@Service
public class QuartzService {
@Resource private RuleLogDAO ruleLogDAO;
}
spring 配置文件
<!-- Configure the sync Service -->
<bean name="randomSyncJob"
class="org.springframework.scheduling.quartz.JobDetailBean">
<property name="jobClass">
<value>com.zqk.cpyj.filter.QuartzSyncJob</value>
</property>
<property name="jobDataAsMap">
<map>
<entry key="quartzService" value-ref="quartzService"/>
</map>
</property>
</bean>
<!-- 配置触发器 -->
<bean id="cronTrigger"
class="org.springframework.scheduling.quartz.CronTriggerBean">
<property name="jobDetail">
<ref bean="randomSyncJob" />
</property>
<!-- 每天0点0分,触发RandomPriceJob,具体说明见附录 -->
<property name="cronExpression">
<value>0 * * * * ?</value>
</property>
</bean>
<bean autowire="no"
class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<!-- 添加触发器 -->
<property name="triggers">
<list>
<ref local="cronTrigger" />
</list>
</property>
</bean>