Customize parameters of a step in Spring Batch application

喜你入骨 提交于 2021-02-11 12:41:17

问题


I am working with Spring Batch(using Spring boot). My requirement is to read data from db, process it(validations and stuffs) and write it to a file. I am trying to achieve this using a batch step.

Problem is, if i define a step, the reader,processor and writer should be having similar parameters.(from examples i saw and the error i got) Like if my reader is returning a db domain object, the processor and writer should be having domain object parameters.

What i am looking for is, reader should return domain object, processor should receive domain object and convert it to dto/pojo(after validations and data conversion) and return dto object. Writer should be receiving dto object and write it to file.

Please let me know if that is possible within a single batch step to have different kind of parameters. If so please give me any example/links to it.


回答1:


Transforming items is a typical use case of an item processor. Here is an excerpt from the ItemProcessor section of the docs:

An ItemProcessor is simple. Given one object, transform it and return another. The provided object may or may not be of the same type

So in your case, the reader can return domain objects which are transformed by an item processor to DTOs. The writer then will get DTOs and write them to the file. Here is a quick example that transforms numbers to strings:

@Bean
public ItemReader<Integer> itemReader() {
    return new ListItemReader<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
}

@Bean
public ItemProcessor<Integer, String> itemProcessor() {
    return item -> "foo" + item;
}

@Bean
public ItemWriter<String> itemWriter() {
    return items -> {
        for (String item : items) {
            System.out.println("item = " + item);
        }
    };
}

@Bean
public Step step() {
    return stepBuilderFactory.get("step")
            .<Integer, String>chunk(5)
            .reader(itemReader())
            .processor(itemProcessor())
            .writer(itemWriter())
            .build();
}


来源:https://stackoverflow.com/questions/58636144/customize-parameters-of-a-step-in-spring-batch-application

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