Spring Batch(modular = true)创建两次作业配置bean

时间:2016-08-10 10:54:00

标签: java spring-batch

@Configuration
@EnableBatchProcessing(modular=true)
public class ModularJobConfiguration {

    @Bean
    public ApplicationContextFactory job() {
        return new GenericApplicationContextFactory(FlatfileToDbJobConfiguration.class);
    }

    @Bean
    public ApplicationContextFactory anotherJob() {
        return new GenericApplicationContextFactory(FlatfileToDbJobAnotherConfiguration.class);
    }

}

例如,只显示一个配置,另一个像这样。

@Configuration
public class FlatfileToDbJobConfiguration {

        @Autowired
        private JobBuilderFactory jobBuilders;

        @Autowired
        private StepBuilderFactory stepBuilders;

        @Bean
        public Job flatfileToDbJob(){
            return jobBuilders.get("flatfileToDbJob")
                    .listener(protocolListener())
                    .start(step())
                    .build();
        }

        @Bean
        public Step step(){
            return stepBuilders.get("step")
                    .<Partner,Partner>chunk(1)
                    .reader(reader())
                    .processor(processor())
                    .writer(writer())
                    .build();
        }

        // ...
        // rest part of code
        // ...
}

一切正常,但配置文件中的所有bean方法都调用了两次。我认为,首先是共同的背景,第二是个人。这是正常的吗?我不能使用post构造,因为它会调用两次。如何使用modular = true并且只有一个bean初始化?谢谢!

1 个答案:

答案 0 :(得分:0)

我找到了答案。我需要@Lazy初始化。然后config将初始化然后单个上下文创建。

@Configuration
@Lazy
public class FlatfileToDbJobConfiguration {

        @Autowired
        private JobBuilderFactory jobBuilders;

        @Autowired
        private StepBuilderFactory stepBuilders;

        @Bean
        public Job flatfileToDbJob(){
            return jobBuilders.get("flatfileToDbJob")
                    .listener(protocolListener())
                    .start(step())
                    .build();
        }

        @Bean
        public Step step(){
            return stepBuilders.get("step")
                    .<Partner,Partner>chunk(1)
                    .reader(reader())
                    .processor(processor())
                    .writer(writer())
                    .build();
        }

        // ...
        // rest part of code
        // ...
}