第一种:
第一步在Spring的配置文件中加入:
value的值是一个key
并且定义service
<bean id="scheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers">
<list>
<ref bean="trigger"></ref>
</list>
</property>
<!--引入jdbc做集群时需要配置的属性-->
<property name="dataSource" ref="datasource"/>
<property name="transactionManager" ref="tx"/>
<property name="configLocation" value="classpath:quartz.properties"/>
<property name="applicationContextSchedulerContextKey" value="springContext"/>
</bean>
<bean id="testService" class="com.etoak.service.TestService">
第二步:
主要流程:
一:调度程序scheduler获取它的上下文
SchedulerContext schedulerContext = scheduler.getContext();
二:调度程序获取通过key值获取对应的springContext上下文
ApplicationContext springContext =
(ApplicationContext) schedulerContext.get(“springContext”);
三:springContext spring上下文通过bean id获取service
TestService testService = springContext.getBean(“testService”, TestService.class);
testService.test();
public class ClusterJob extends QuartzJobBean {
@Override
protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
Scheduler scheduler=context.getScheduler();
try {
SchedulerContext schedulerContext = scheduler.getContext();
ApplicationContext springContext =
(ApplicationContext) schedulerContext.get("springContext");
TestService testService = springContext.getBean("testService", TestService.class);
testService.test();
} catch (SchedulerException e) {
e.printStackTrace();
}
}
}
第二种:
在整合Quartz的配置文件中配置:
第一步:配置数据源
<bean id="datasource" class="com.zaxxer.hikari.HikariDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="jdbcUrl" value="jdbc:mysql://127.0.0.1/quarzt"/>
<property name="username" value="root"/>
<property name="password" value="sw1996"/>
</bean>
第二步:事务管理器
<bean id="tx" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="datasource"/>
</bean>
第三步:最重要的一步 配置SchedulerFactoryBean
<!--SchedulerFactoryBean-->
<bean id="scheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="dataSource" ref="datasource"/>
<property name="transactionManager" ref="tx"/>
<property name="configLocation" value="classpath:quartz.properties"/>
<!--第二种获取spring ioc容器的方式-->
<property name="jobFactory">
<bean class="com.etoak.factory.EtoakJobFactory"/>
</property>
</bean>
在jobFactory类中:
public class JobFactory extends SpringBeanFactory{
@Autowired
AutowireCapableBeanFactory factory;
@Override
protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {
//获取MvcJob
Object jobInstance = super.createJobInstance(bundle);
//将job装到Spring容器中
factory.autowireBean(jobInstance);
return jobInstance;
}