Home > OS >  Field jobLauncher in com.example.demo.config.BatchLaunche that could not be found
Field jobLauncher in com.example.demo.config.BatchLaunche that could not be found

Time:03-03

Field jobLauncher in com.example.demo.config.BatchLauncher required a bean of type 'org.springframework.batch.core.launch.JobLauncher' that could not be found.

The injection point has the following annotations: - @org.springframework.beans.factory.annotation.Autowired(required=true)

Action:

Consider defining a bean of type 'org.springframework.batch.core.launch.JobLauncher' in your configuration.

@Component
public class BatchLauncher {
    
    @Autowired
    private JobLauncher jobLauncher;
    
    @Autowired
    private Job job;

    public BatchStatus run() throws JobParametersInvalidException, JobExecutionAlreadyRunningException,
            JobRestartException, JobInstanceAlreadyCompleteException {
        JobParameters parameters = new JobParametersBuilder().addLong("time", System.currentTimeMillis())
                .toJobParameters();
        JobExecution jobExecution = jobLauncher.run(job, parameters);
        return jobExecution.getStatus();
    }
}

CodePudding user response:

You have many ways to resolve it, all of them is to resolve the been detection of JobLuncher in Spring IOC container as exception says the IOC can not locate the bean for JobLuncher class to inject in the BatchLuncher class, simple using @Autowired is not enough at all actually you are telling the IOC the instance of JobLuncher class will be provided but at compile time he can not locate the instance to inject so you need to provide an instance of it.

  • Add the @Service or @Component annotation to the implementation of your JobLuncher.
  • Inject the instance of JobLuncher class in some custom class annotated by @Config and annotate the method injector of JobLuncher by @Bean to scan by IOC .
    @Configuration
    public class JobLuncherConfig {
        @Bean
        public JobLuncher jobLuncher() {
        //return an implementation or concrete class of JobLuncher class-interface
          return new JobLuncher(...);
        }
    }

Indeed there are many other ways as well, more over i recommend to have more depth look on Spring container and inversion of control, you may start from here .

  • Related