简体   繁体   中英

Spring @Autowired beans are null - how to find the mistake

I integrated Spring batch and the quartz timer into my Spring-MVC application. Currently I have several directories:

@Autowire works everywhere but in MyBatchJob.java (-> code compiles but properties are NULL during runtime)

- batch
    +- MyProcessor
    +- MyReader
    +- MyWriter
    +- MyListener
- config
    +- MainConfig
    +- BatchConfig
- controller
[...]
- schedule
    +- MyBatchJob

BatchConfig is annotated with:

@Configuration
@ComponentScan(basePackages = "my.backend.schedule")
@EnableBatchProcessing // imports jobLauncher, stepBuilderFactory, jobBuilderFactory, ...
public class BatchConfig {

    @Bean
    public JobDetail jobDetail() {
        return newJob(MyBatchJob.class)
            .withIdentity("name", "group")
            .build();
    }

and imported in MainConfig using @Import(BatchConfig.class) . In this configuration file and in the controllers I can @Autowire the classes I need. But it does not work in my my.backend.schedule.MyBatchJob class:

@Component
public class MyBatchJob implements org.quartz.Job {

    @Autowired
    JobLauncher jobLauncher; // null

    @Autowired
    StepBuilderFactory stepBuilderFactory; // null

    @Autowired
    JobBuilderFactory jobBuilderFactory; // null

What is the reason for this, how can I find and fix it?

Meta: I already searched a lot and saw many threads here on SO - but did not find the solution. I already know how the spring beans live inside the container but that does not give me the answer - I may overlook something.

edit: additional information as requested inserted into BatchConfig class above.

edit2: Changing to JobDetailFactoryBean:

BatchConfig:

@Bean
public JobDetailFactoryBean jobDetailFactory() {
    JobDetailFactoryBean factory = new JobDetailFactoryBean();
    factory.setJobClass(MyBatchJob.class);
    return factory;
}

@Bean
public Trigger myJobTrigger() throws Exception {

    SchedulerFactory schedulerFactory = new StdSchedulerFactory();
    Scheduler scheduler = schedulerFactory.getScheduler();
    scheduler.start();

    Trigger trigger = newTrigger()
            .withIdentity("mySynchTrigger", "synch")
            .startNow()
            .withSchedule(simpleSchedule()
                .withIntervalInSeconds(30) // testing
                .repeatForever())
            .build();
    scheduler.scheduleJob(jobDetailFactory().getObject(), trigger);
    return trigger;
}

您应该按此处所述注册JobDetailFactoryBean ,而不要自己使用Quartz API。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM