Spring Batch Hello World Example Code
Spring Batch is the core framework for building enterprise-grade data integration solutions. It simplifies the development of complex ETL (Extract, Transform, Load) tasks through declarative programming and robust job scheduling capabilities. Before deeply mastering its core concepts, we must clearly define the lifecycle of a batch processing task: from creating a Job instance via the launcher, to executing Steps with state management, finally completing data flow and recording result logs. This entire process relies on abstract interfaces provided by the Spring Batch Core module, such as Job, Step, ItemReader, ItemProcessor, and ItemWriter. These components collaborate together to handle ordered reading of large-scale data, logical transformation, and persistent output.
To quickly get started with Spring Batch, we will begin with an extremely minimal "Hello World" example demonstrating how to define and execute the first batch processing task. This example aims to showcase basic usage of core components without involving complex business logic or external database dependencies; it simulates data reading and writing processes solely through in-memory streams. We will use Java 8+ features combined with Spring Boot Starter Batch for development, ensuring code conciseness and portability.
First, introduce the necessary dependency items into your project's pom.xml file:
- Spring Batch Core: Provides core runtime support;
- Spring Boot Starters: Simplifies configuration and startup processes;
- Jackson (Optional): Used for serializing and deserializing example data objects.
Next is the code implementation section, where we will define three key components separately: a Reader, a Processor, and a Writer. These classes typically inherit from Spring Batch-provided abstract base classes ItemReader, ItemProcessor, and ItemWriter to leverage the framework's built-in state management mechanisms. Below is a complete example structure:
package com.example.batch;
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.item.ItemCallbackHandler;
import java.util.Arrays;
import java.util.List;
public class HelloBatchExample {
public static void main(String[] args) throws Exception {
// Define a simple Job containing one Step
var job = new com.example.job.HelloWorldJob();
// Create and execute the Step, listening for step events
var stepContribution = job.execute(new org.springframework.batch.core.StepExecutionListener() {
@Override
public void beforeStep(org.springframework.batch.core.StepContext context,
org.springframework.batch.core.Step step) throws Exception {
System.out.println("Step started: Hello World");
}
@Override
public void afterStep(StepContribution contribution, StepExecution execution) throws Exception {
if (execution.isCompleted()) {
System.out.println("Processing completed! Read and output " +
((List<String>)contribution.getOutput()).size() + " items");
} else {
throw new RuntimeException("Step execution failed: " + step.getName());
}
}
@Override
public void onStepFailure(StepExecution execution, StepException exception) throws Exception {
System.err.println("Critical error: " + exception.getMessage());
}
});
job.run(stepContribution);
}
}
The above code demonstrates how to control the execution flow via Job and Step, while listening for step start and end events. In practical applications, you can replace the data source with database query result sets or file readers; processors can incorporate business logic (such as format conversion or filtering); writers are responsible for submitting processed data to target storage systems.
Extended Practice: Migrating from Memory Streams to Real-World Scenarios
Once the basic framework understanding is complete, it is recommended to try introducing real ItemReader and ItemWriter instances to simulate processes closer to production environments. For example, you can customize a FileItemReader to read each line string in a CSV file, then use a simple Processor to clean up data (such as removing leading/trailing spaces), and finally employ a JdbcBatchItemWriter to batch insert the results into a MySQL database.
During this process, pay close attention to the following points:
- Transaction Consistency: Ensure clear transaction boundaries within each Step;
- Exception Handling Mechanism: Utilize Spring Batch-provided callback interfaces to capture and log failure reasons;
- Performance Optimization Strategies: Reasonably set batch sizes (Batch Size) to improve throughput.
By iteratively refining the above examples, you will gradually build mastery over the entire lifecycle of Spring Batch, laying a solid foundation for learning complex scheduling, monitoring, and fault tolerance mechanisms later on.