1.Quartz 整合 spring 进行 web简单开发测试:
测试项目; 建立maven 项目 ,打包方式 war 包 .
导入maven 依赖;
quartz 依赖:
spring依赖
日志相关依赖: // 不影响正常开发.
tomcat 插件:
配置web.xml spring 监听
编写示例代码:
public class HellowJob implements Job {
public void execute(JobExecutionContext arg0) throws JobExecutionException {
System.out.println("Hellow Quartz");
}
}
在spring配置文件 配置 ;
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd ">
<!-- 定义 job -->
<bean id="myJob"
class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
<property name="jobClass" value="com.njsc.HellowJob" />
</bean>
<!-- 定义trigger -->
<bean id="myTrigger1"
class="org.springframework.scheduling.quartz.SimpleTriggerFactoryBean">
<property name="jobDetail" ref="myJob" />
<!-- 3秒后第一次执行 -->
<property name="startDelay" value="3000" />
<!-- 5秒后重复执行 -->
<property name="repeatInterval" value="5000" />
</bean>
<!-- scheduler -->
<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers">
<list>
<ref bean="myTrigger1"/>
</list>
</property>
</bean>
</beans>
Quartz 和 spring整合 bean 注入问题:
示例: 新建
@Service
public class HelloService {
public void sayHello(){
System.out.println(" Hello Quartz_Spring ..........");
}
}
修改Hellowjob工作任务类
public class HellowJob implements Job {
@Autowired
private HelloService helloService;
public void execute(JobExecutionContext arg0) throws JobExecutionException {
helloService.sayHello();
}
}
运行maven 项目: 日志如下
helloService 实例并没有 注入经 HellowJob 中 出现空指针;
解决: 需要在Scheduler 中 自定义jobFactory
@Service("jobFactory")
public class JobFactory extends AdaptableJobFactory {
@Autowired
private AutowireCapableBeanFactory capableBeanFactory;
@Override
protected Object createJobInstance(TriggerFiredBundle bundle)
throws Exception {
Object jobInstance = super.createJobInstance(bundle);
capableBeanFactory.autowireBean(jobInstance);
return jobInstance;
}
}
配置applicationContext.xml
运行maven 项目: