Springboot+quartz job注入问题

在quartz 会发现 job中无法注入springboot管理的类

解决方法:新建Jobfactory类

@Component
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;
  }
}

新建QuartzConfig类

@Configuration
@EnableScheduling
public class QuartzConfig{
  @Autowired
  JobFactory jobfactory;
  @Bean
  public SchedulerFactoryBean schedulerFactoryBean() throws IOException{
  SchedulerFactoryBean factory=new SchedulerFactoryBean();
  factory.setOverwriteExistingJobs(true);
  //延时启动
  factory.setStartupDelay(20);
  //自定义JobFactory,用于Spring注入
  factory.setJobFactory(jobFactory);
  return factory;
  }
}

之后在配置job时
@Autowired
SchedulerFactoryBean schedulerFactoryBean;
即可

你可能感兴趣的:(Springboot+quartz job注入问题)