eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – Summer Sale 2026 – NPI EA (cat= Baeldung)
announcement - icon

Yes, we're now running our only Summer Sale. All Courses are 30% off until 20th July, 2026:

>> EXPLORE ACCESS NOW

Course – Summer Sale 2026 – NPI (cat=Baeldung)
announcement - icon

Yes, we're now running our only Summer Sale. All Courses are 30% off until 20th July, 2026:

>> EXPLORE ACCESS NOW

1. Introduction

Spring Batch provides robust mechanisms for restarting failed jobs. These mechanisms allow jobs to resume processing from the point of failure. This capability is essential for handling large-scale data processing tasks efficiently.

Spring Batch’s built-in JobRepository persists job execution state. This allows for default restartability of jobs. As a result, a failed job can resume exactly where it left off. This ensures that no duplicate processing or data loss occurs.

In this tutorial, we’ll look at how to configure and restart a failed Spring Batch job effectively.

2. Maven Dependencies

Let’s start by importing the spring-boot-starter-batch, spring-boot-starter-data-jpa, and h2 dependencies to our pom.xml:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-batch</artifactId>
    <version>3.3.2</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
    <version>3.3.2</version>
</dependency>
	  
<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <version>2.2.224</version>
</dependency>

We need the file-based H2 database to enable job restartability by persisting job execution state across application runs.

3. Defining a Simple Spring Batch Job

In this section, we’ll explore a Spring Batch job configuration that demonstrates a simple batch processing workflow. We’ll define a job with one step: processing a CSV file.

In Spring Boot 3, we should avoid using @EnableBatchProcessing as it disables Spring Boot’s helpful auto-configuration (like creation of Spring Batch tables).

3.1. Configuration

Let’s create the BatchConfig class, which sets up a job named simpleJob:

@Configuration
public class BatchConfig {

    @Bean
    public Job simpleJob(JobRepository jobRepository, PlatformTransactionManager transactionManager) {
        return new JobBuilder("simpleJob", jobRepository)
          .start(step1(jobRepository, transactionManager))
          .build();
    }
}

The simpleJob bean defines the batch job using JobBuilder. The job consists of one step: step1, which reads, processes, and writes a CSV file:

@Bean
public Step step1(JobRepository jobRepository, PlatformTransactionManager transactionManager) {
    return new StepBuilder("step1", jobRepository)
      .<String, String>chunk(2, transactionManager)
      .reader(flatFileItemReader())
      .processor(itemProcessor())
      .writer(itemWriter())
      .build();
}

Step 1 defines a chunk-based step using the StepBuilder. This step processes data in batches of two items at a time, reading strings from a FlatFileItemReader, transforming them with an ItemProcessor, and writing the results using an ItemWriter – all managed within a transaction controlled by the PlatformTransactionManager to ensure data integrity.

The JobRepository persists the step’s execution state, including the FlatFileItemReader’s position, enabling restartability from the last uncommitted chunk if the job fails.

3.2. Item Reader

Let’s define the flatFileItemReader bean that provides the input data:

@Bean
@StepScope
public FlatFileItemReader<String> flatFileItemReader() {
    return new FlatFileItemReaderBuilder<String>()
      .name("itemReader")
      .resource(new ClassPathResource("data.csv"))
      .lineMapper(new PassThroughLineMapper())
      .saveState(true)
      .build();
}

The code defines a FlatFileItemReader<String> bean named flatFileItemReader with @StepScope to ensure a new instance is created for each step execution, enabling proper state management and restartability. It reads strings from a data.csv file located in the classpath, maps each line to a string using a PassThroughLineMapper.

Also, it has saveState(true) to persist its read position in the ExecutionContext. This allows the reader to resume from the last unprocessed line in case of a job failure, leveraging the JobRepository for state persistence.

For a job to be truly restartable, the ItemReader must persist its state in Spring Batch’s execution context. Readers like FlatFileItemReader automatically save critical progress information (such as line numbers or record counts) between chunks.

3.3. Item Processor

Let’s declare the itemProcessor bean that transforms the input data:

@Bean
public RestartItemProcessor itemProcessor() {
    return new RestartItemProcessor();
}

static class RestartItemProcessor implements ItemProcessor<String, String> {
    private boolean failOnItem3 = true;

    public void setFailOnItem3(boolean failOnItem3) {
        this.failOnItem3 = failOnItem3;
    }

    @Override
    public String process(String item) throws Exception {
        System.out.println("Processing: " + item + " (failOnItem3=" + failOnItem3 + ")");
        if (failOnItem3 && item.equals("Item3")) {
            throw new RuntimeException("Simulated failure on Item3");
        }
        return "PROCESSED " + item;
    }
}

It processes each item by prefixing it with PROCESSED and simulates a failure on Item3.

3.4. Item Writer

Now, let’s create the itemWriter bean that outputs the processed data:

@Bean
public ItemWriter<String> itemWriter() {
    return items -> {
      System.out.println("Writing items:");
      for (String item : items) {
          System.out.println("- " + item);
      }
    };
}

This prints processed items to the console. Now, our application is ready.

4. Restarting a Failed Spring Batch Job

Spring Batch jobs are designed to be restartable by default, allowing them to seamlessly resume from the point of failure. Consequently, no additional configuration is required to enable this functionality.

However, for this to work effectively, the job state must be persisted in a JobRepository. Furthermore, the JobRepository must be backed by a database to ensure reliable storage and retrieval of the job’s execution state.

The following subsections describe how to simulate a job failure and restart it.

4.1. Simulating a Job Failure

To simulate a job failure, the ItemProcessor is configured to throw a RuntimeException when processing Item3. When the failure occurs on Item3, the JobRepository stores this state, marking the job as FAILED.

Running the application with mvn spring-boot:run produces:

Starting new job execution...
Processing: Item1
Processing: Item2
Writing items:
- PROCESSED Item1
- PROCESSED Item2
Processing: Item3
[Exception: Simulated failure on Item3]
Job started with status: FAILED

This output confirms that Item1 and Item2 are processed and written, but the failure on Item3 halts the job, with the state persisted for a subsequent restart.

4.2. Restarting the Job

To restart the failed job, we use the CommandLineRunner to detect the failed job instance using the JobExplorer and the fixed JobParameters:

@Bean
CommandLineRunner run(JobLauncher jobLauncher, Job job, JobExplorer jobExplorer,
    JobOperator jobOperator, BatchConfig.RestartItemProcessor itemProcessor) {
    return args -> {
      JobParameters jobParameters = new JobParametersBuilder()
        .addString("jobId", "test-job-" + System.currentTimeMillis())
        .toJobParameters();

      List<JobInstance> instances = jobExplorer.getJobInstances("simpleJob", 0, 1);
      if (!instances.isEmpty()) {
          JobInstance lastInstance = instances.get(0);
          List<JobExecution> executions = jobExplorer.getJobExecutions(lastInstance);
          if (!executions.isEmpty()) {
              JobExecution lastExecution = executions.get(0);
              if (lastExecution.getStatus() == BatchStatus.FAILED) {
                  itemProcessor.setFailOnItem3(false);

                  JobExecution restartedExecution = jobLauncher.run(job, jobParameters);

                  // final Long restartId = jobOperator.restart(lastExecution.getId());
                  // final JobExecution restartedExecution = jobExplorer.getJobExecution(restartedExecution);

                  // ...
              }
          }
      }

    };
}

The code checks the job repository via JobExplorer for any existing instances of simpleJob.

It detects a failed execution with a status of FAILED. It uses JobLauncher.run() or JobOperator.restart() to resume that specific job. The job resumes from its last persisted state. This ensures previously processed items aren’t reprocessed.

To ignore the failure on Item3 during the restart, we set itemProcessor.setFailOnItem3(false) before launching the restarted job, allowing the RestartItemProcessor to process Item3 without throwing an exception.

Now, we run the application again.

Let’s check the output:

Restarting failed job execution with ID: [execution_id]
Processing: Item3
Processing: Item4
Writing items:
- PROCESSED Item3
- PROCESSED Item4
Processing: Item5
Writing items:
- PROCESSED Item5
Restarted job status: COMPLETED

The Spring Batch job had failed on Item3. It successfully restarted from the failure point. Then, the job processed Item3 to Item5 in chunks, wrote the results, and completed with a COMPLETED status.

4.3. Testing the Job Restart

Let’s add a unit test to verify Spring Batch’s job restart functionality instead of using a CommandLineRunner:

@Test
public void givenItems_whenFailed_thenRestartFromFailure() throws Exception {
    // Given
    createTestFile("Item1\nItem2\nItem3\nItem4");

    JobParameters jobParameters = new JobParametersBuilder()
      .addLong("time", System.currentTimeMillis())
      .toJobParameters();

    // When
    JobExecution firstExecution = jobLauncherTestUtils.launchJob(jobParameters);
    assertEquals(BatchStatus.FAILED, firstExecution.getStatus());

    Long executionId = firstExecution.getId();

    itemProcessor.setFailOnItem3(false);

    // Then
    JobExecution restartedExecution = jobLauncherTestUtils.launchJob(jobParameters);

    assertEquals(BatchStatus.COMPLETED, restartedExecution.getStatus());

    assertEquals(
      firstExecution.getJobInstance().getInstanceId(),
      restartedExecution.getJobInstance().getInstanceId()
    );
}

The test method first executes a job that intentionally fails when processing Item3 (asserting the expected FAILED status). Then, it modifies the processor behavior to no longer fail on that item. Finally, it restarts the job with the same parameters to confirm it can successfully complete from the point of failure.

The test validates three key aspects. First, it confirms that the initial failure occurs as designed, testing the fault simulation. Next, it ensures the restarted job continues processing from the point of failure, verifying restart logic. Finally, it checks that both executions belong to the same job instance, validating instance tracking.

4.4. Preventing the Job Restart

We can prevent to restart the job using the preventRestart() method:

@Bean
public Job simpleJob(JobRepository jobRepository, PlatformTransactionManager transactionManager) {
    return new JobBuilder("simpleJob", jobRepository)
      .start(step1(jobRepository, transactionManager))
      .preventRestart()
      .build();
}

Adding .preventRestart() to the JobBuilder configures the job to always start from the beginning (e.g., Item1) rather than resuming from the point of failure (e.g., Item3) when relaunched. This overrides Spring Batch’s default behavior of persisting the job state in the JobRepository for restart purposes.

5. Conclusion

Spring Batch’s default restartability enables robust recovery from job failures, ensuring that a failed job can resume from the point of failure without reprocessing completed items or losing data.

In this article, we created a simple job that demonstrated this restart capability. We configured a job to process items in chunks, simulating a failure at Item3. Upon restarting, the job resumed from Item3, processed through Item5, and completed successfully with a COMPLETED status.

We also explored how to override this behavior using preventRestart() on the JobBuilder. This forces the job to start from the beginning, like Item1, instead of resuming from the failure point.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

Course – Summer Sale 2026 – NPI EA (cat= Baeldung)
announcement - icon

Yes, we're now running our only Summer Sale. All Courses are 30% off until 20th July, 2026:

>> EXPLORE ACCESS NOW

Course – Summer Sale 2026 – NPI (All)
announcement - icon

Yes, we're now running our only Summer Sale. All Courses are 30% off until 20th July, 2026:

>> EXPLORE ACCESS NOW

eBook Jackson – NPI EA – 3 (cat = Jackson)