How to Use Tasklet in Spring Batch with Spring Boot
If youβre working on Spring Batch and looking for a simple way to define your job logic, Tasklet is the perfect choice. In this post, weβll walk through what a Tasklet is, when to use it, and how to implement it using Spring Boot 3+ and Spring Batch 5+.
π What Is a Tasklet?
A Tasklet is a functional interface in Spring Batch that allows you to perform a single task inside a step. Think of it as a method that gets called once per execution and finishes with a status like RepeatStatus.FINISHED
.
β When Should You Use Tasklets?
- When your step logic is simple or one-off (e.g. cleaning temp files, sending emails, etc.)
- When you donβt need chunk-based processing
- For quick validations, archiving, logging, or calling APIs
π§± Maven Dependency
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-batch</artifactId>
</dependency>
βοΈ Create a Tasklet
Hereβs how you can define a tasklet using a lambda expression (supported in Spring Batch 5.x):
@Bean
public Step taskletStep() {
return new StepBuilder("sample-tasklet-step",repository)
.tasklet((contribution, chunkContext) -> {
System.out.println("Executing tasklet logic");
return RepeatStatus.FINISHED;
},platformTransactionManager).build();
}
π§© Job Configuration
@Bean
public Job taskletJob() {
return new JobBuilder("sample-job",repository).incrementer(new RunIdIncrementer())
.start(taskletStep())
.build();
}
π Output
When you run the application, you should see:
Executing Tasklet logic...
π‘ Tips
- Use
PlatformTransactionManager
explicitly with Spring Batch 5+ - Lambda-based tasklets are cleaner and easier to read
- Use Tasklet when your logic is short and single-pass
π― Conclusion
Tasklet is a powerful but lightweight way to define your step logic in Spring Batch. Itβs ideal for quick, one-time operations that donβt require chunking.