Spring @Autowired bean为null - 如何找到错误

时间:2014-12-23 14:18:00

标签: java spring spring-mvc autowired

我将Spring批处理和石英计时器集成到我的Spring-MVC应用程序中。目前我有几个目录:

@Autowire无处不在,但在MyBatchJob.java中( - >代码编译但在运行时属性为NULL)

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

BatchConfig注释为:

@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();
    }

并使用@Import(BatchConfig.class)在MainConfig中导入。在这个配置文件和控制器中,我可以@Autowire我需要的类。但它在我的my.backend.schedule.MyBatchJob类中不起作用:

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

    @Autowired
    JobLauncher jobLauncher; // null

    @Autowired
    StepBuilderFactory stepBuilderFactory; // null

    @Autowired
    JobBuilderFactory jobBuilderFactory; // null

这是什么原因,我该如何找到并修复它?

Meta:我已经搜索了很多,并在SO上看到了很多线程 - 但没有找到解决方案。我已经知道春豆是如何生活在容器内的,但这并没有给我答案 - 我可能会忽略一些事情。

编辑:在上面的BatchConfig类中插入请求的附加信息。

edit2:更改为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;
}

1 个答案:

答案 0 :(得分:0)

您应该按照JobDetailFactoryBean所述注册here,而不是自己使用Quartz API。