问题
具体问题就是需要在具体任务Job中使用@Autowired
注入自己的Service。但一直报空指针异常。原因是因为job的实例化在quartz进行,和Spring托管的Service啥的不是一条路,所以关联不到一起
翻遍了csdn也没找到好的解决方案,甚至还有配置xml的,那还用什么Springboot。
解决方案一
最后找了一个比较完整且靠谱的帖子,但是也没有解决问题。在调试中我发现,通过@Bean
来注入的SchedulerFactoryBean
竟然没有被任何类引用。原来是因为已经有个名字叫做"SchedulerFactoryBean"的类被注入到Spring中了(springboot干的),所以这里我换了名,成功解决。
这里我放上QuarzConfig的代码,其余部分和这里一样
https://blog.youkuaiyun.com/u013042707/article/details/82934725
@Configuration
public class QuartzConfig {
@Autowired
private MyJobFactory myJobFactory;
@Autowired
@Qualifier("schedulerFactoryBean2")
private SchedulerFactoryBean schedulerFactoryBean;
@Bean
public SchedulerFactoryBean schedulerFactoryBean2(){
SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();
schedulerFactoryBean.setOverwriteExistingJobs(true);
schedulerFactoryBean.setJobFactory(myJobFactory);
return schedulerFactoryBean;
}
/**
* 初始注入scheduler
*/
@Bean
public Scheduler scheduler(){
return schedulerFactoryBean.getScheduler();
}
}
待定方案二
不一定有用,可以尝试一下。在运用自己的Service.doSomething前,用这种方式获取Service对象。getBean里面是自定义的Service名
MyService myService= (MyService) SpringContextUtils.getBean("myService");
其中SpringContextUtils代码为:
@Component
public class SpringContextUtils implements ApplicationContextAware {
public static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
SpringContextUtils.applicationContext = applicationContext;
}
public static Object getBean(String name) {
return applicationContext.getBean(name);
}
public static <T> T getBean(String name, Class<T> requiredType) {
return applicationContext.getBean(name, requiredType);
}
public static boolean containsBean(String name) {
return applicationContext.containsBean(name);
}
public static boolean isSingleton(String name) {
return applicationContext.isSingleton(name);
}
public static Class<? extends Object> getType(String name) {
return applicationContext.getType(name);
}
}