How to apply something like @Lazy to Spring Batch?

不打扰是莪最后的温柔 提交于 2021-02-04 06:53:00

问题


I have a Spring Batch project with multiple jobs (job A, job B, job C,...). When I run a particular job A, I got the log of the job A shows that all of the beans of job B, C,... are created too. Is there any way to avoid the creation of the other beans when job A is launched.

I have tried to use @Lazy annotation but it 's seem not working.

@Configuration
@EnableBatchProcessing
public class BatchConfiguration {

    @Autowired
    public JobBuilderFactory jobBuilderFactory;

    @Autowired
    public StepBuilderFactory stepBuilderFactory;

    @Autowired
    @Qualifier("springDataSource")
    public DataSource springDataSource;

    @Autowired
    @Qualifier("batchJobDataSource")
    public DataSource batchJobDataSource;

}


@Configuration
@PropertySource("classpath:partner.properties")
public class B extends BatchConfiguration {


    @Value("${partnerId}")
    private String partnerId;

    @Lazy
    @Bean
    public Job ProcessB(JobCompletionNotificationListener listener) {
      return jobBuilderFactory
        .get("ProcessB")
        .incrementer(new RunIdIncrementer())
        .listener(listener)
        .start(ProcessStepB())
        .build();
    }

    @Lazy
    @Bean
    public Step (ProcessStepB() {
        return stepBuilderFactory
                .get("(ProcessStepB")
                .<PartnerDTO, PartnerDTO> chunk(1)
                .reader(getPartner())
                .processor(process())
                .writer(save())
                .build();
    }

    @Lazy
    @Bean(destroyMethod = "")
    public Reader getPartner() {    
        return new Reader(batchJobDataSource,partnerId);
    }

    @Lazy
    @Bean
    public Processor process() {
        return new Processor();
    }

    @Lazy
    @Bean
    HistoryWriter historyWriter() {
        return new HistoryWriter(batchJobDataSource);
    }

    @Lazy
    @Bean
    UpdateWriter updateWriter() {
        return new UpdateWriter(batchJobDataSource);
    }

    @Lazy
    @Bean
    public CompositeItemWriter<PartnerDTO> saveTransaction() {
        List<ItemWriter<? super PartnerDTO>> delegates = new ArrayList<>();
        delegates.add(updateWriter());
        delegates.add(historyWriter());
        CompositeItemWriter<PartnerDTO> itemWriter = new CompositeItemWriter<>();
        itemWriter.setDelegates(delegates);
        return itemWriter;
    }
}

I have also put the @Lazy over the @Configuration but it does work too.


回答1:


That should not be an issue. But here are a few ideas to try:

  • Use Spring profiles to isolate job beans
  • If you use Spring Boot 2.2+, try to activate the lazy bean initialization mode
  • Package each job in its own jar. This is the best option IMO.


来源:https://stackoverflow.com/questions/60349214/how-to-apply-something-like-lazy-to-spring-batch

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!