spring quartz整合实现定时器自动注解

时间:2023-03-09 05:25:38
spring quartz整合实现定时器自动注解

1.web.xml中添加侦听器

  <listener>
      <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 
    </listener>

2.提供自动注解实现类

  /**
  * Copyright 2011-2013 Brin.com
  * All rights reserved.
  *
  * @project
  * @author Brin
  * @version 1.0
  * @data 2013-10-10
  */
  package com.brin.core.common.quartz;

  import org.quartz.spi.TriggerFiredBundle;
  import org.springframework.beans.BeansException;
  import org.springframework.context.ApplicationContext;
  import org.springframework.context.ApplicationContextAware;
  import org.springframework.scheduling.quartz.SpringBeanJobFactory;

  /**
  * @description 为定时器提供自动注入功能
  * @author Brin
  *
  */
  public class JobFactory extends SpringBeanJobFactory implements ApplicationContextAware {

    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
      this.applicationContext = applicationContext;
    }

    @Override
    protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {
      Object jobInstance = super.createJobInstance(bundle);
      applicationContext.getAutowireCapableBeanFactory().autowireBean(jobInstance);
      return jobInstance;
    }
  }

3.quartz.xml中配置jobFactory

  <beans:bean id="schedulerFactory" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
    <beans:property name="jobFactory">
      <beans:bean class="com.brin.core.common.quartz.JobFactory"/>
    </beans:property>
    <beans:property name="triggers">
      <beans:list>
        <beans:ref bean="remindersTimer"/>
      </beans:list>
    </beans:property>
  </beans:bean>

定时器中的@Autowired注入的类,可以实例化