quartz timed task -- Job cannot inject service @Autowired automatically. The injection is null

Keywords: SpringBoot Spring

The pit stepped by Quartz's scheduled task

Cannot inject service or @ Autowired to null

When quartz is integrated with springboot, when quartzJob is injected into redisService, null is always reported

At first, I thought it was spring that was not configured correctly. After "small degree", I knew it was quartz's configuration reason

There are two areas that need to be adjusted:

1. Add a class MyJobFactory

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 MyJobFactory extends SpringBeanJobFactory {

    @Autowired
    private AutowireCapableBeanFactory capableBeanFactory;

    @Override
    protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {
        //Call the method of the parent class
        Object jobInstance = super.createJobInstance(bundle);
        //Injection
        capableBeanFactory.autowireBean(jobInstance);
        return jobInstance;
    }

}

2. The second adjustment is to add MyJobFactory to the configuration file

/**
     * Initial injection scheduler
     * @return
     * @throws SchedulerException
     */
    @Bean
    public Scheduler scheduler(SchedulerFactoryBean schedulerFactoryBean) throws SchedulerException{
        return schedulerFactoryBean.getScheduler();
    }


    @Bean
    public MyJobFactory jobFactory(){
        return new MyJobFactory();
    }

    @Bean
    public SchedulerFactoryBean schedulerFactoryBean(MyJobFactory jobFactory){
        SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();
        schedulerFactoryBean.setJobFactory(jobFactory);
        return schedulerFactoryBean;
    }

Note: inject the bean (MyJobFactory), put the jobFactory into the SchedulerFactoryBean, and obtain the scheduler of the SchedulerFactoryBean when injecting the scheduler; in this way, add the customized jobFactory to the configuration file.

Self test code, perfect customs clearance!

 

Blog reference https://blog.csdn.net/huangjp_hz/article/details/70064316

Posted by jeff8j on Thu, 02 Jan 2020 07:10:37 -0800