After a chat that got deeper into this issue, the real "issue" is that the ItemReader is being created once instead of once per REST call (aka once per execution of the job). To fix this, make the ItemReader step scoped. This will allow you to get a new instance of the reader with each run which also enables the ability to inject the file name base on job parameters.

From a code perspective, change this:

@Bean
public ItemReader<Person> reader() {

to this:

@Bean
@StepScope
public FlatFileItemReader<Person> reader() {

The reason for the return type change is that Spring Batch will automatically register ItemStreams for you. However when using @StepScope we only see the return you define. In this case, ItemReader doesn't extend/implement ItemStream so we don't know you're returning something we should be auto-registering. By returning FlatFileItemReader we can see all the interfaces/etc and can apply the "magic" for you.

Answer from Michael Minella on Stack Overflow
🌐
GitHub
github.com › chrisgleissner › spring-batch-rest
GitHub - chrisgleissner/spring-batch-rest: REST API for Spring Batch using Spring Boot 2.2 · GitHub
Start job execution (synchronous or asynchronous) with optional job property overrides. The job properties can either be obtained via a custom API or via standard Spring Batch job parameters, accessible from step-scoped beans. To integrate the REST API in your Spring Boot project, first ensure ...
Starred by 91 users
Forked by 44 users
Languages   Java 99.9% | Procfile 0.1%
🌐
Medium
medium.com › @andrejtaneski › using-spring-batch-in-a-rest-api-application-493b812d80d1
Using Spring Batch in a REST API Application | by Andrej Taneski | Medium
March 24, 2023 - Spring Batch offers so much more than the example described in this post so be sure to refer to the official documentation. Here we looked at an example of how to define job steps, jobs and how to run jobs asynchronously from a REST controller. What you might want to do next is provide means for the users of the API ...
🌐
Petri Kainulainen
petrikainulainen.net › home › blog › spring batch tutorial: reading information from a rest api
Spring Batch Tutorial: Reading Information From a REST API - Petri Kainulainen
December 21, 2020 - Spring Batch has a good support for reading data from different data sources such as files (CSV or XML) or databases. However, it doesn’t have a built-in support for reading input data from a REST API. If you want to use a REST API as a data source of your Spring Batch job, you have […]
🌐
YouTube
youtube.com › watch
Spring Batch with REST API and SQL DB using Spring Boot - YouTube
In this video, I will explain the architecture, when to use spring batch, how to trigger the spring batch either automatically or by rest API with SQL DB, an...
Published   September 12, 2022
Top answer
1 of 2
2

You have to build job with JobbuilderFactory:

    @Configuration
@EnableBatchProcessing
public class BatchConfiguration {

    @Autowired
    public JobBuilderFactory jobBuilderFactory;

    @Autowired
    public StepBuilderFactory stepBuilderFactory;

    @Bean
    public SomeReader<Some> reader() {

        // some reader configuration
        return reader;
    }

    @Bean
    public SomeProcessor processor() {
        return new SomeProcessor();
    }

    @Bean
    public SomeWriter<Person> writer() {
        // some config
        return writer;
    }

    @Bean
    public Job someJob() {
        return jobBuilderFactory.get("someJob")
                .flow(step1())
                .end()
                .build();
    }

    @Bean
    public Step step1() {
        return stepBuilderFactory.get("step1")
                .<Some, Some> chunk(10)
                .reader(reader())
                .processor(processor())
                .writer(writer())
                .build();
    }
    }

Start job in rest controller:

@RestController
@AllArgsConstructor
@Slf4j
public class BatchStartController {

    JobLauncher jobLauncher;

    Job job;

    @GetMapping("/job")
    public void startJob() {
    //some parameters
        Map<String, JobParameter> parameters = new HashMap<>();
        JobExecution jobExecution = jobLauncher.run(job, new JobParameters(parameters));
        }    }

And one important detail - add in application.properties:

spring.batch.job.enabled=false

to prevent job self start.

2 of 2
0

Solved by myself, as suggested here: Spring Boot: Cannot access REST Controller on localhost (404)

@SpringBootApplication
@EnableBatchProcessing
@EnableScheduling
@ComponentScan(basePackageClasses = JobStatusApi.class)
public class UpdateInfoBatchApplication {
    
    public static void main(String[] args) {
        SpringApplication.run(UpdateInfoBatchApplication.class, args);
    }
    
}
🌐
Medium
prateek-ashtikar512.medium.com › spring-batch-read-from-rest-api-990d03208c1
Spring Batch — read from REST API - Prateek
September 4, 2023 - @SpringBootApplication @EnableBatchProcessing @EnableScheduling public class SpringBatchExampleApplication implements CommandLineRunner { @Autowired private Job job; @Autowired private JobLauncher jobLauncher; @Bean RestTemplate restTemplate() { return new RestTemplate(); } public static void main(String[] args) { SpringApplication.run(SpringBatchExampleApplication.class, args); } @Override public void run(String... args) throws Exception { jobLauncher.run(job, newExecution()); } private JobParameters newExecution() { Map<String, JobParameter> parameters = new HashMap<>(); JobParameter paramet
🌐
Javainuse
javainuse.com › spring › springbootbatchtaskscheduler
Spring Boot Batch Job + Scheduler Simple Example
In a previous post we had implemented a Spring Boot Hello World Application. In that the Batch Job got triggered by a REST API call. In this post we develop a simple Spring Boot Batch application where batch job gets triggered using a scheduler. Consider the simple use case where the user wants ...
Find elsewhere
🌐
GitHub
github.com › nicoraynaud › spring-batch-rest-api
GitHub - nicoraynaud/spring-batch-rest-api: Spring Boot library that exposes a REST API to manage Spring batch (start, stop, list, search jobs, job executions and history) · GitHub
Spring Boot library that exposes a REST API to manage Spring batch (start, stop, list, search jobs, job executions and history) - nicoraynaud/spring-batch-rest-api
Starred by 6 users
Forked by 15 users
Languages   Java 99.7% | Shell 0.3%
🌐
GitHub
github.com › officiallysingh › spring-boot-batch-web
GitHub - officiallysingh/spring-boot-batch-web: Spring batch job as Spring Rest service
Spring batch job as Spring Rest service. Contribute to officiallysingh/spring-boot-batch-web development by creating an account on GitHub.
Author   officiallysingh
🌐
Keitaro
keitaro.com › insights › 2023 › 03 › 23 › using-spring-batch-in-a-rest-api-application
Using Spring Batch in a REST API Application – Keitaro
March 23, 2023 - Spring Batch offers so much more than the example described in this post, so be sure to refer to the official documentation. Here we looked at an example of how to define job steps, jobs, and how to run jobs asynchronously from a REST controller. What you might want to do next is provide means for the API ...
🌐
YouTube
youtube.com › watch
Spring Batch Read File, Consume REST, Schedule Job | Spring Boot 3, Spring Batch, Scheduler - YouTube
In this video, we implement Spring Batch functionality using different approaches.The first approach is using Spring Batch Chunk to read CSV files, process d...
Published   September 5, 2023
🌐
Stack Overflow
stackoverflow.com › questions › 69066493 › how-to-initiate-a-spring-batch-job-from-a-restcontroller-passing-an-arry-of-str
java - How to initiate a Spring Batch job from a RestController, passing an arry of Strings to the job? - Stack Overflow
September 5, 2021 - Copy@Configuration @Log4j2 public class AddComicsConfiguration { private static final String KEY_STARTED = "job.started"; @Autowired public JobBuilderFactory jobBuilderFactory; @Autowired public StepBuilderFactory stepBuilderFactory; @Autowired private JobLauncher jobLauncher; @Autowired private ComicInsertObjectReader comicInsertObjectReader; @Autowired private ComicInsertProcessor comicInsertProcessor; @Autowired private ComicInsertWriter comicInsertWriter; @Value("${batch.chunk-size}") private int batchChunkSize = 10; @Bean @Qualifier("addComicsJob") public Job addComicsToLibraryJob() { ret
🌐
Quora
quora.com › How-do-you-write-a-spring-boot-batch-API-When-an-API-get-request-is-triggered-the-batch-job-should-be-triggered-which-reads-the-data-from-the-flat-file-and-then-writes-it-into-the-DB-or-another-file
How do you write a spring boot batch API? When an API get request is triggered, the batch job should be triggered which reads the data fr...
Answer: To write a Spring Boot batch API that starts a batch job when a GET request is made: 1. Create a Spring Boot project. 2. Define a batch job class that implements the [code ]Job[/code] interface. 3. Configure the batch job in a Batchcofig class. 4. Create a REST endpoint to start the batc...
🌐
Stack Overflow
stackoverflow.com › questions › 20248910 › how-to-trigger-a-job-using-a-rest-web-service
spring batch - How to trigger a job using a rest web service? - Stack Overflow
November 28, 2013 - ... This is not a place where ask for code! Try yourself and if you will be in trouble post your problem, we will be happy to help you! ... You can start the spring batch from your rest Put/Post method.
🌐
GitHub
github.com › chaitanyaankam › spring-batch-using-rest
GitHub - chaitanyaankam/spring-batch-using-rest: Spring Batch and Spring REST example; Batch controlled and monitored through REST API's exposed
Spring Batch and Spring REST example (Loading Data form CSV to Database using spring batch framework). Batch controlled and monitored through REST API's exposed (Starting, Aborting, Restarting and Monitoring). Resources loaded from Batch are exposed through Spring REST (Exposing Data loaded ...
Author   chaitanyaankam
Top answer
1 of 2
2

It is possible to create your own custom ItemWriter.

In your case, please add the spring-boot-starter-web dependency to either your pom.xml or build.gradle

Example:

package com.example.batch;

import lombok.extern.log4j.Log4j2;
import org.springframework.batch.item.ItemWriter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@Log4j2
public class RestItemWriter implements ItemWriter<String> {
    @Autowired
    RestTemplate restTemplate;

    public RestItemWriter(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    @Override
    public void write(List<? extends String> items) throws Exception {
        ResponseEntity<Users> users = restTemplate.getForEntity("https://jsonplaceholder.typicode.com/users/1", Users.class);

        log.info("Status code is: " + users.getStatusCode());
    }
}


package com.example.batch;

import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Users {

    public String id;
    public String name;
    public String username;
    public String email;
    public String phone;
}

More information about custom item writers here

2 of 2
1

Of course! you can send the processed records to another system using REST call in ItemWriter.

Use the below code in your RestItemWriter class.

private RestTemplate restTemplate;

@Override
public void write(@NonNull Chunk<? extends Payload> chunk) throws Exception {

    for((Payload payload : chunk){

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization", "xx-tokenString-xx");
                    
        HttpEntity<Payload> requestEntity = new HttpEntity<>(payload, headers);

        try{
            ResponseEntity<Object> response = restTemplate.exchange(url, HttpMethod.PATCH, requestEntity, Object.class);
            LOGGER.info("Request hits the server {}", response.getBody());
        } catch(HttpClientErrorException e){
            LOGGER.error("HttpClientErrorException occured during connection {}", e.getMessage());
        } catch (Exception e) {
            LOGGER.error("Exception occured during connection {}", e.getMessage());
        }

    }
}

To make HTTP Patch request using RestTemplate, below configurations are mandatory, for other HTTP calls you may ignore it.

 @Bean
    public RestTemplate restTemplate() {
        LOGGER.info("restTemplate Bean has bean created");
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient);
        RestTemplate restTemplate = new RestTemplate(factory);
        return restTemplate;
    }

You have to add the below dependency in pom.xml to use CloseableHttpClient, and HttpClients.

<dependency>
    <groupId>org.apache.httpcomponents.client5</groupId>
    <artifactId>httpclient5</artifactId>
</dependency>