javaspringspring-mvcspring-batchspring-framework-beans

how can i execute constructor only when i execute batch process?


I'm making batch process using spring batch.

I intend to integrate spring batch into spring-webmvc project.

But, when I start spring-webmvc server, spring batch's ItemReader, ItemProcessor, ItemWriter Constructors called.

I used constructors to get batch data from database, so I expect database's data will be remained in memory.

I think it may cause waste of memory.

So how can I call these constructors only when I execute batch process?

Here is my batch configuration.

@Configuration
@EnableBatchProcessing
public class DbSyncConfiguration {
  @Autowired
  private JobBuilderFactory jobBuilderFactory;
  @Autowired
  private StepBuilderFactory stepBuilderFactory;
  private final int BATCH_SIZE = 1000;



  @Bean
  public Job dbSyncJob() {
    return this.jobBuilderFactory.get("dbSyncJob")
            .incrementer(new RunIdIncrementer())
            .start(this.userParseStep())
            .build();
  }

  @Bean
  public Step userParseStep() {
    return this.stepBuilderFactory.get("userParseStep")
            .<ParseItem, ParseItem>chunk(BATCH_SIZE)
            .reader(new UserItemParseReader())
            .writer(new UserItemParseWriter())
            .build();
  }
}

Solution

  • You can lazy initialize spring configuration for batch for this case.

    Refer:
    https://www.baeldung.com/spring-lazy-annotation. https://howtodoinjava.com/spring5/core/spring-bean-eager-vs-lazy-init/