Springboot + quartz 无法使用@Autowired注入Service的问题

问题

具体问题就是需要在具体任务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);
    }

}
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值