Spring Boot Rest API + Spring Batch

I'm studying the Spring Batch process, but the documentation for me not clarifying the flow.

I have one API that receives one flat file wit fixed positions. The file has a header, body, and footer specific layouts.

I thinking to create a File class that has one Header, a list of Details and a footer class.

All I know from now is that I have to use one Token to identify the positions for each header, detail, and footer, but everything I found about the Spring batch not shows how to do it and start the process from the API request.

Upvotes: 5

Views: 12212

Answers (2)

AndreaNobili
AndreaNobili

Reputation: 42957

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);
    }
    
}

Upvotes: 0

Valeriy K.
Valeriy K.

Reputation: 2904

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.

Upvotes: 2

Related Questions