16 Temmuz 2018 Pazartesi

SpringBatch @StepScope Anotasyonu

Giriş
Açıklaması şöyle.
by specifying a spring batch component being StepScope means that Spring Batch will use the spring container to instantiate a new instance of that component for each step execution.
Örnek
Şöyle yaparız
@Configuration
@EnableBatchProcessing
public class JobConfig {

  @Autowired
  private JobBuilderFactory jobBuilderFactory;

  @Autowired
  private StepBuilderFactory stepBuilderFactory;

  @Autowired
  private DataSource dataSource;

  @Bean
  public Job job() {
    return jobBuilderFactory.get("job")
      .incrementer(new RunIdIncrementer())
      .start(step())
      .build();
    }

  @Bean
  public Step step() {
    return stepBuilderFactory.get("step")
      .<String, String>chunk(10)
      .reader(reader())
      .processor(processor())
      .writer(writer())
      .build();
  }
}
Şöyle yaparız
@Bean
@StepScope
public FlatFileItemReader<String> reader() {
  return new FlatFileItemReaderBuilder<String>()
    .name("reader")
    .resource(new ClassPathResource("input.csv"))
    .lineMapper(new DefaultLineMapper<String>() {{
      setLineTokenizer(new DelimitedLineTokenizer() {{
        setNames(new String[]{"name"});
      }});
      setFieldSetMapper(new BeanWrapperFieldSetMapper<String>() {{
        setTargetType(String.class);
      }});
    }})
    .build();
}

@Bean
@StepScope
public ItemProcessor<String, String> processor() {
  return item -> item.toUpperCase();
}

@Bean
@StepScope
public JdbcBatchItemWriter<String> writer() {
  return new JdbcBatchItemWriterBuilder<String>()
    .dataSource(dataSource)
    .sql("INSERT INTO output(name) VALUES (:name)")
    .itemSqlParameterSourceProvider(new BeanPropertyItemSqlParameterSourceProvider<>())
    .build();
}

Hiç yorum yok:

Yorum Gönder