Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Spring Batch with Spring Boot Tutorial

Introduction to Spring Batch

Spring Batch is a powerful framework for building batch processing applications. It provides reusable functions essential for processing large volumes of data, including logging, transaction management, and job processing. When combined with Spring Boot, it simplifies the setup and configuration needed to run batch jobs.

Setting Up the Project

To create a Spring Batch application with Spring Boot, you can use Spring Initializr to generate a project with the required dependencies.

1. Go to Spring Initializr.

2. Select the following options:

  • Project: Maven Project
  • Language: Java
  • Spring Boot: Choose the latest stable version
  • Dependencies: Spring Batch, Spring Web, H2 Database

3. Click "Generate" to download the project.

Project Structure

After extracting the generated project, your directory structure should look similar to this:

                └── spring-batch-demo
                    ├── src
                    │   ├── main
                    │   │   ├── java
                    │   │   │   └── com
                    │   │   │       └── example
                    │   │   │           └── springbatchdemo
                    │   │   │               ├── SpringBatchDemoApplication.java
                    │   │   │               └── config
                    │   │   │                   └── BatchConfig.java
                    │   │   └── resources
                    │   │       └── application.properties
                    └── pom.xml
                

Configuring Spring Batch

In the BatchConfig.java file, you will configure the necessary batch components such as job, step, and item reader/writer.

Here is an example configuration:

                import org.springframework.batch.core.Step;
                import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
                import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
                import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
                import org.springframework.batch.core.launch.support.RunIdIncrementer;
                import org.springframework.batch.core.Job;
                import org.springframework.batch.item.ItemProcessor;
                import org.springframework.batch.item.ItemReader;
                import org.springframework.batch.item.ItemWriter;
                import org.springframework.context.annotation.Bean;
                import org.springframework.context.annotation.Configuration;

                @Configuration
                @EnableBatchProcessing
                public class BatchConfig {
                    
                    @Bean
                    public Job job(JobBuilderFactory jobBuilderFactory, StepBuilderFactory stepBuilderFactory) {
                        return jobBuilderFactory.get("job")
                                .incrementer(new RunIdIncrementer())
                                .flow(step(stepBuilderFactory))
                                .end()
                                .build();
                    }

                    @Bean
                    public Step step(StepBuilderFactory stepBuilderFactory) {
                        return stepBuilderFactory.get("step")
                                .chunk(10)
                                .reader(itemReader())
                                .processor(itemProcessor())
                                .writer(itemWriter())
                                .build();
                    }

                    @Bean
                    public ItemReader itemReader() {
                        // Implement your item reader
                    }

                    @Bean
                    public ItemProcessor itemProcessor() {
                        // Implement your item processor
                    }

                    @Bean
                    public ItemWriter itemWriter() {
                        // Implement your item writer
                    }
                }
                

Implementing Item Reader, Processor, and Writer

You need to implement the item reader, processor, and writer as per your requirements. Here’s an example of each:

Item Reader

                import org.springframework.batch.item.ItemReader;

                public class SimpleItemReader implements ItemReader {
                    private String[] items = {"Item1", "Item2", "Item3"};
                    private int index = 0;

                    @Override
                    public String read() {
                        if (index < items.length) {
                            return items[index++];
                        } else {
                            return null; // End of input
                        }
                    }
                }
                

Item Processor

                import org.springframework.batch.item.ItemProcessor;

                public class SimpleItemProcessor implements ItemProcessor {
                    @Override
                    public String process(String item) {
                        return item.toUpperCase(); // Example processing
                    }
                }
                

Item Writer

                import org.springframework.batch.item.ItemWriter;

                import java.util.List;

                public class SimpleItemWriter implements ItemWriter {
                    @Override
                    public void write(List items) {
                        items.forEach(System.out::println); // Example writing
                    }
                }
                

Running the Batch Job

You can run your batch job by simply executing the Spring Boot application. Use the following command in the terminal:

./mvnw spring-boot:run

Once the application starts, the batch job will run automatically, and you should see the output in the console.

Conclusion

In this tutorial, we have covered the basics of setting up a Spring Batch application using Spring Boot. You learned how to configure batch jobs, implement item readers, processors, and writers, and run the batch job. Spring Batch provides a robust framework for handling batch processing needs, and integrating it with Spring Boot makes the development process much easier.