一.问题背景
1.1 环境
- spring-boot 2.1.0.RELEASE
- spring-boot-starter-quartz 2.1.0.RELEASE
1.2 解决job中无法注入bean
这个问题网上一搜索一堆教程,大致意思就是需要自定义一个JobFactory,继承org.springframework.scheduling.quartz.AdaptableJobFactory,然后重写其中的createJobInstance方法以达到注入的目的.
代码如下:
import org.quartz.spi.TriggerFiredBundle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.scheduling.quartz.AdaptableJobFactory;
import org.springframework.stereotype.Component;
@Component
public class AutowiredableJobFactory extends AdaptableJobFactory
{
@Autowired
private AutowireCapableBeanFactory capableBeanFactory;
@Override
protected Object createJobInstance(TriggerFiredBundle bundle) {
// 实例化对象
Object jobInstance = super.createJobInstance(bundle);
// 进行注入(Spring管理该Bean)
capableBeanFactory.autowireBean(jobInstance);
//返回对象
return jobInstance;
}
}
然后就解决了在job中@Autowired的对象会是null的问题了.
1.3 新的问题
但是这样会有一个问题,在新版IDEA中,如果你使用@Autowired注解来注入,会给出如下提示
Field injection is not recommended
为什么会提示这个呢?百度一下,得到的答案是这样:
使用变量依赖注入的方式是不被推荐的
Always use constructor based dependency injection in your beans. Always use assertions for mandatory dependencies
推荐使用构造器强制注入
那么,当我选择这种推荐写法后,代码如下
@Component
public class DemoTask implements Job {
private final DemoService demoService;
public DemoTask(DemoService demoService){
this.demoService = demoService;
}
}
在启动的时候,报了如下错误
org.quartz.SchedulerException: Job instantiation failed
at org.springframework.scheduling.quartz.AdaptableJobFactory.newJob(AdaptableJobFactory.java:47)
at org.quartz.core.JobRunShell.initialize(JobRunShell.java:127)
at org.quartz.core