本文介绍了在 Spring Batch 应用程序中自定义步骤的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Spring Batch(使用 Spring Boot).我的要求是从数据库读取数据,处理它(验证和东西)并将其写入文件.我正在尝试使用批处理步骤来实现这一点.

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.

我要找的是,读取器应该返回域对象,处理器应该接收域对象并将其转换为 dto/pojo(经过验证和数据转换)并返回 dto 对象.Writer 应该接收 dto 对象并将其写入文件.

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.

推荐答案

转换项是项处理器的典型用例.以下是 ItemProcessor 文档部分:

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

ItemProcessor 很简单.给定一个对象,转换它并返回另一个.提供的对象可能是也可能不是同一类型

因此,在您的情况下,阅读器可以返回由项目处理器转换为 DTO 的域对象.然后编写器将获取 DTO 并将它们写入文件.这是一个将数字转换为字符串的简单示例:

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();
}

这篇关于在 Spring Batch 应用程序中自定义步骤的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-03 21:54
查看更多