Spring Batch — ItemReader

Prateek
3 min readJul 17, 2021

--

ItemReader — Strategy interface for providing the data. Implementations are expected to be stateful and will be called multiple times for each batch, with each call to read() returning a different value and finally returning null when all input data is exhausted. Implementations need not be thread-safe and clients of a ItemReader need to be aware that this is the case. A richer interface (e.g. with a look ahead or peek) is not feasible because we need to support transactions in an asynchronous batch.

SimpleItemReader.java

public class SimpleItemReader implements ItemReader<String> {

private List<String> dataSet = new ArrayList<>();

private Iterator<String> iterator;

public SimpleItemReader() {
this.dataSet.add("1");
this.dataSet.add("2");
this.dataSet.add("3");
this.dataSet.add("4");
this.dataSet.add("5");
this.iterator = this.dataSet.iterator();
}

@Override
public String read() throws Exception, UnexpectedInputException, ParseException, NonTransientResourceException {
return iterator.hasNext() ? iterator.next():null;
}

}

MainApp.java

@SpringBootApplication
@EnableBatchProcessing
public class MainBatchApplication {

@Autowired
public JobBuilderFactory jobBuilderFactory;

@Autowired
public StepBuilderFactory stepBuilderFactory;

@Bean
public ItemReader<String> itemReader() {
return new SimpleItemReader();
}

@Bean
public Step chunkBasedStep() {
return this.stepBuilderFactory.get("chunkBasedStep")
.<String,String>chunk(3)
.reader(itemReader())
.writer(getWriter())
.build();
}

private ItemWriter<String> getWriter() {
return items -> {
System.out.println(String.format("Received list of size: %s", items.size()));
items.forEach(System.out::println);
};
}


@Bean
public Job job() {
return this.jobBuilderFactory.get("job")
.start(chunkBasedStep())
.build();
}

public static void main(String[] args) {
SpringApplication.run(MainBatchApplication.class, args);
}
}

Console

.   ____          _            __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.5.2)

2021-07-18 00:04:17.611 INFO 16664 --- [ main] com.example.demo.DemoApplication : Starting DemoApplication using Java 15.0.1 on DESKTOP-NQ639DU with PID 16664 (C:\Users\pc\Downloads\demo\demo\target\classes started by pc in C:\Users\pc\Downloads\demo\demo)
2021-07-18 00:04:17.615 INFO 16664 --- [ main] com.example.demo.DemoApplication : No active profile set, falling back to default profiles: default
2021-07-18 00:04:20.210 INFO 16664 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2021-07-18 00:04:20.920 INFO 16664 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2021-07-18 00:04:21.265 INFO 16664 --- [ main] o.s.b.c.r.s.JobRepositoryFactoryBean : No database type set, using meta data indicating: H2
2021-07-18 00:04:21.621 INFO 16664 --- [ main] o.s.b.c.l.support.SimpleJobLauncher : No TaskExecutor has been set, defaulting to synchronous executor.
2021-07-18 00:04:21.868 INFO 16664 --- [ main] com.example.demo.DemoApplication : Started DemoApplication in 5.317 seconds (JVM running for 6.122)
2021-07-18 00:04:21.872 INFO 16664 --- [ main] o.s.b.a.b.JobLauncherApplicationRunner : Running default command line with: []
2021-07-18 00:04:22.008 INFO 16664 --- [ main] o.s.b.c.l.support.SimpleJobLauncher : Job: [SimpleJob: [name=job]] launched with the following parameters: [{}]
2021-07-18 00:04:22.102 INFO 16664 --- [ main] o.s.batch.core.job.SimpleStepHandler : Executing step: [chunkBasedStep]
Received list of size: 3
1
2
3
Received list of size: 2
4
5

2021-07-18 00:04:22.175 INFO 16664 --- [ main] o.s.batch.core.step.AbstractStep : Step: [chunkBasedStep] executed in 45ms
2021-07-18 00:04:22.185 INFO 16664 --- [ main] o.s.b.c.l.support.SimpleJobLauncher : Job: [SimpleJob: [name=job]] completed with the following parameters: [{}] and the following status: [COMPLETED] in 122ms
2021-07-18 00:04:22.218 INFO 16664 --- [ionShutdownHook] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown initiated...
2021-07-18 00:04:22.223 INFO 16664 --- [ionShutdownHook] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown completed.

--

--

Prateek
Prateek

Written by Prateek

Java Developer and enthusiast

No responses yet