错误:字段作业中需要一个类型为'org.springframework.batch.core.JobLauncher'的bean,但找不到该bean

fykwrbwg  于 2023-03-23  发布在  Spring
关注(0)|答案(2)|浏览(216)

下面是我的2类应用程序和配置

package com.spring;

import org.springframework.batch.core.Job;
import org.springframework.context.annotation.Bean;

public class Configuration {
    @Bean
    Job testRun() {
        return null;
    }
}
package com.spring;

import org.springframework.batch.core.Job;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App implements CommandLineRunner {

    @Autowired
    JobLauncher jobLauncher;

    @Autowired
    Job testRun;

    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        // TODO Auto-generated method stub
        System.out.println("RUNNING ...");
        jobLauncher.run(testRun, null);
    }   

}

然而,当我尝试执行这个命令时,我得到了错误:

***************************
APPLICATION FAILED TO START
***************************

Description:

Field jobLauncher in com.spark.spring.App 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.

我在这里错过了什么吗?我相信我已经定义了JobLauncher和Job bean。还有,为什么我需要为Job Launcher定义一个bean?

aelbi1ox

aelbi1ox1#

您需要将Configuration类作为Spring配置类,这意味着使用@Configuration注解它,如下所示:

@Configuration
public class Configuration {

    @Bean
    Job testRun() {
        return null;
    }

}

此外,根据您报告的错误,您需要在该配置类(或其他地方)中定义JobLauncher类型的bean,或者添加@EnableBatchProcessing注解,它将自动为您创建它:

@Configuration
@EnableBatchProcessing
public class Configuration {

    @Bean
    Job testRun() {
        return null;
    }

}
raogr8fs

raogr8fs2#

检查pom.xml中的spring-boot-starter-parent版本。尝试将其设置为2.7.9版本或更早版本。

相关问题