Search code examples
spring-bootspring-batch

Error : Field job in required a bean of type 'org.springframework.batch.core.Job' that could not be found


I am a beginner with spring batch, and I developped a simple project with it . I am getting the error.

Description:
Field job in com.example.demo.DemoApplication required a bean of type 
'org.springframework.batch.core.Job' that could not be found.
Action:
Consider defining a bean of type 'org.springframework.batch.core.Job' in your 
configuration.

Here is my code, I have just one class :

package com.example.demo;

import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

@SpringBootApplication
@EnableScheduling
@EnableBatchProcessing
public class DemoApplication {

    @Autowired
    private JobLauncher jobLauncher;

    @Autowired
    private Job job;
  
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

    @Scheduled(cron = "0 */1 * * * ?")
    public void perform() throws Exception {
        JobParameters params = new JobParametersBuilder()
                .addString("JobID", String.valueOf(System.currentTimeMillis()))
                .toJobParameters();
        jobLauncher.run(job, params);
    }
}

Thanks for helping me to find the mainly cause of this error


Solution

  • It looks like you do not have a Job bean defined in your application context or the job is not found by Spring Boot.

    Make sure the configuration class in which you define your batch job is in the package (or sub-package) scanned by your Spring Boot app (which is com.example.demo according to your sample).