Spring quartz Job依赖注入使用详解
SpringquartzJob依赖注入使用详解
一、问题描述:
使用Spring整合quartz实现动态任务时,想在job定时任务中使用某个service时,直接通过加注解@Component、@Autowired是不能注入的,获取的对象为Null。如下面的代码:
@Component
@PersistJobDataAfterExecution
@DisallowConcurrentExecution
publicclassTicketSalePriceLessThanLowestPriceJobimplementsJob{
@Autowired
privateXxxServicexxxService;
}
二、解决方案:
1、新增一个自定义类(CustomJobFactory),继承SpringBeanJobFactory,代码如下:
importorg.quartz.spi.TriggerFiredBundle;
importorg.springframework.beans.factory.annotation.Autowired;
importorg.springframework.beans.factory.config.AutowireCapableBeanFactory;
importorg.springframework.scheduling.quartz.SpringBeanJobFactory;
publicclassCustomJobFactoryextendsSpringBeanJobFactory{
@Autowired
privateAutowireCapableBeanFactorycapableBeanFactory;
@Override
protectedObjectcreateJobInstance(TriggerFiredBundlebundle)throwsException{
//调用父类的方法
ObjectjobInstance=super.createJobInstance(bundle);
//进行注入
capableBeanFactory.autowireBean(jobInstance);
returnjobInstance;
}
}
2、在spring.xml文件配置CustomJobFactory,如下:
3、将自定义CustomJobFactory注入到org.springframework.scheduling.quartz.SchedulerFactoryBean,具体如下:
完整代码如下:
4、然后就可以在Job任务类使用@Autowired注入service。
如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下