解决Spring整合quartz Job时Bean不能依赖注入的问题

一、问题描述

项目环境:Spring项目整合org.quartz-scheduler

问题描述:实现Job类的类中,不能使用@Autowired自动注入Bean

二、解决教程

  • 新建CustomJobFactory类
import org.quartz.spi.TriggerFiredBundle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.scheduling.quartz.SpringBeanJobFactory;

public class CustomJobFactory extends SpringBeanJobFactory{
	
	@Autowired    
    private AutowireCapableBeanFactory capableBeanFactory;    
    
    @Override    
    protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {    
        //调用父类的方法    
        Object jobInstance = super.createJobInstance(bundle);    
        //进行注入    
        capableBeanFactory.autowireBean(jobInstance);    
        return jobInstance;    
    }

}
  • 配置spring-context.xml

	
  

    
    
      
  • 使用方式
@DisallowConcurrentExecution  
public class testJob implements Job{  
  
    @Autowired  
    private XxxService xxxService;  

    public void execute(JobExecutionContext context) throws JobExecutionException {
        // ***
    }

}

以上配置即可解决spring bean在quartz-scheduler中不能自动注入的问题。

你可能感兴趣的:(Spring,spring,quartz)