如何在石英中自动装配?

时间:2018-02-02 07:34:22

标签: spring quartz-scheduler autowired lifecycle quartz

之前我曾将它设置为石英作业中的自动装配 注意here

但是,工作内部类的自动装配将失败。

我的工作代码示例就在这里。

DEFAULT NONE

Do.java

NOT NULL

为什么会发生这种情况? 我该如何解决它以及我应该了解哪些概念?

1 个答案:

答案 0 :(得分:1)

Quartz作业不在spring的相同上下文中运行,因此autowired对象在同一个类中变为null。你必须让Quartz Spring知道。

首先添加sprint-context-support

<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-context-support</artifactId>
  <version>${spring.version}</version>
</dependency>

然后创建一个应用程序上下文持有者,它是应用程序上下文感知

@Component
public final class ApplicationContextHolder extends SpringBeanJobFactory implements ApplicationContextAware {

  private static ApplicationContext context;

  private transient AutowireCapableBeanFactory beanFactory;

  @Override
  public void setApplicationContext(ApplicationContext ctx) throws BeansException {
    beanFactory = ctx.getAutowireCapableBeanFactory();
    context = ctx;
  }

  @Override
  protected Object createJobInstance(final TriggerFiredBundle bundle) throws Exception {
    final Object job = super.createJobInstance(bundle);
    beanFactory.autowireBean(job);
    return job;
  }

  public static ApplicationContext getContext() {
    return context;
  }
}

然后您可以创建Quartz Scheduler配置类

@Configuration
public class QuartzSchedulerConfiguration {

  @Autowired
  private ApplicationContext applicationContext;

  /**
   * Create the job factory bean
   * @return Job factory bean
   */
  @Bean
  public JobFactory jobFactory() {
    ApplicationContextHolder jobFactory = new ApplicationContextHolder();
    jobFactory.setApplicationContext(applicationContext);
    return jobFactory;
  }

  /**
   * Create the Scheduler Factory bean
   * @return scheduler factory object
   */
  @Bean
  public SchedulerFactoryBean schedulerFactory() {
    SchedulerFactoryBean factory = new SchedulerFactoryBean();
    factory.setAutoStartup(true);
    factory.setSchedulerName("My Scheduler");
    factory.setOverwriteExistingJobs(true);
    factory.setJobFactory(jobFactory());
    return factory;
  }
}

现在,这会将您的石英调度程序放在与Spring相同的上下文中,因此您现在可以创建一个SchedulerService类。

@Service
public class SchedulerService {

  @Autowired
  private SchedulerFactoryBean schedulerFactory;

  private Scheduler scheduler;

  /**
   * Initialize the scheduler service
   */
  @PostConstruct
  private void init() {
    scheduler = schedulerFactory.getScheduler();
  }
}

现在您可以使用scheduler对象使用方法填充此类来创建日程表,并且当触发任务时,扩展Job的类将使用spring进行上下文感知,并且自动装配的对象将不再为null < / p>

解决后续问题实施ApplicationContextHolder组件,然后将其自动装入您的SchedulerConfig班级

@Autowire
ApplicationContextHolder holder

@Bean
// injecting SpringLiquibase to ensure liquibase is already initialized and created the quartz tables: 
public JobFactory jobFactory(SpringLiquibase springLiquibase) {
  AutowiringSpringBeanJobFactory jobFactory = new AutowiringSpringBeanJobFactory();
  jobFactory.setApplicationContext(holder);
  return jobFactory;
}