构造函数中的参数 0 需要一个无法找到的“java.lang.String”类型的 bean

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/52841620/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 00:37:51  来源:igfitidea点击:

Parameter 0 of constructor in required a bean of type 'java.lang.String' that could not be found

javaspring-bootspring-batchspring-annotations

提问by Ganesh

I am working on spring batch with spring boot 2.X application, actually its existing code i am checked out from git. While running the application it fails due to below error only for me and same code is working for others.

我正在使用 spring boot 2.X 应用程序处理 spring 批处理,实际上它的现有代码是我从 git 中检出的。运行该应用程序时,由于以下错误而失败,仅对我而言,相同的代码对其他人也有效。

s.c.a.AnnotationConfigApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'inputItemReader' defined in file [C:\Users\XYZ\git\main\batch\CBatchProcessing\target\classes\com\main\batchprocessing\batch\reader\InputItemReader.class]: Unsatisfied dependency expressed through **constructor parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'java.lang.String' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations**: {}


Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2018-10-16 23:23:37.411 ERROR 2384 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   : 

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

Description:

**Parameter 0 of constructor in com.main.batchprocessing.batch.reader.InputItemReader required a bean of type 'java.lang.String' that could not be found.**


Action:

Consider defining a bean of type 'java.lang.String' in your configuration.

I have checked below

我在下面检查过

  1. All Spring components are correctly annotated with @Component, @Service, @Controller,@Repository, etc...
  2. @ComponentScan & @EnableAutoCOnfiguration is also provided.
  3. Tried giving "java.lang.String" in declarations.
  1. 所有 Spring 组件都使用@Component、@Service、@Controller、@Repository 等正确注释...
  2. 还提供了@ComponentScan 和@EnableAutoCONfiguration。
  3. 尝试在声明中给出“java.lang.String”。

Code:

代码:

    import java.util.Map;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.batch.core.ExitStatus;
    import org.springframework.batch.core.StepExecution;
    import org.springframework.batch.core.StepExecutionListener;
    import org.springframework.batch.item.file.FlatFileItemReader;
    import org.springframework.batch.item.file.mapping.JsonLineMapper;
    import 
    org.springframework.batch.item.file.separator.JsonRecordSeparatorPolicy;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.context.annotation.Bean;
    import org.springframework.core.io.FileSystemResource;
    import org.springframework.stereotype.Component;

    @Component
    public class InputItemReader extends  FlatFileItemReader<Map<String, 
     Object>> implements StepExecutionListener {

    @Autowired
    private InputFileHeaderValidator inputFileHeaderValidator; 

    @Autowired
    private FileAuditService fileAuditService;

    private final Logger log = 
    LoggerFactory.getLogger(InputItemReader.class);

    private java.lang.String inputFilePath;

    public InputItemReader(String inputFilePath) {
        setLineMapper(new JsonLineMapper());
        setRecordSeparatorPolicy(new JsonRecordSeparatorPolicy());
        setResource(new FileSystemResource(inputFilePath));
        this.inputFilePath = inputFilePath;
    }
   }

采纳答案by v_schoener

Since you do not provide the public default constructor and you added your own non-default constructor the instantiation will fail. I would suggest you to define the input file path as property like @Value("${inputFilePath}"). If you need further initialization in your bean define a void method and annotate it with @PostConstructand do the initialization within.

由于您没有提供公共默认构造函数并且您添加了自己的非默认构造函数,因此实例化将失败。我建议您将输入文件路径定义为@Value("${inputFilePath}"). 如果您需要在 bean 中进一步初始化,请定义一个 void 方法并使用它进行注释@PostConstruct并在其中进行初始化。

回答by Adina Fometescu

You defined something like this:

你定义了这样的东西:

@Component
public class InputItemReader{

   public InputItemReader(String input){
     ...
   }
}

The name of your class suggest that your object is not a bean, just a simple object. You should try to use it in classic way:

你的类的名称表明你的对象不是一个 bean,只是一个简单的对象。您应该尝试以经典方式使用它:

new InputItemReader(myString);

or to have a static method to process the input String.

或者有一个静态方法来处理输入字符串。

Explanation: Spring IoC container will try to instantiate a new InputItemReader object like this :

说明:Spring IoC 容器将尝试实例化一个新的 InputItemReader 对象,如下所示:

new InputItemReader( -- WHAT TO PUT HERE? --) 

and will fail to call your constructor, because it will not know what you do actually expect and input string.

并且将无法调用您的构造函数,因为它不知道您实际期望和输入字符串做什么。

UPDATE: Your problem can be solved by removing @Component annotation and defining the bean in a configuration like this:

更新:您的问题可以通过删除 @Component 注释并在如下配置中定义 bean 来解决:

@Bean
public InputItemReader inputItemReader(InputFileHeaderValidator inputFileHeaderValidator, FileAuditService fileAuditService){
    InputItemReader inputItemReader = new InputItemReader("--HERE SHOULD BE ACTUAL PATH---");
    // set the required service, a cleaner approach would be to send them via constructor
    inputItemReader.setFilteAuditService(fileAuditService);
    inputItemReader.setInputFileHeaderValidator(inputFileHeaderValidator);
    return inputItemReader;
}

回答by vkstream

Add a public default constructorin your class. For example.

在您的类中添加一个公共默认构造函数。例如。

public User() {
}

回答by Riccardo Bonesi

I also had the same error:

我也有同样的错误:

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

Description:

Field repository in com.example.controller.CampaignController required a bean of type 'com.example.data.CustomerRepository' that could not be found.


Action:

Consider defining a bean of type 'com.example.data.CustomerRepository' in your configuration.de here

I solved this issue by adding @EnableMongoRepositoriesannotation in the main class:

我通过@EnableMongoRepositories在主类中添加注释解决了这个问题:

@SpringBootApplication
@EnableMongoRepositories(basePackageClasses = CustomerRepository.class)
public class CampaignAPI {

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

回答by Kailas010

Make sure you are using spring-boot-starter-data-jpa

确保您使用的是 spring-boot-starter-data-jpa

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

回答by hernanemartinez

in my case, the issue was way different.

就我而言,问题完全不同。

@SpringBootApplication
@EnableNeo4jRepositories("com.digital.api.repositories") // <-- This was non-existent.
public class Application {

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

Look at the @EnableNeo4jRepositories annotation. The package defined, was non-existent. Try defining that package, and be careful that the Repository interfaces are based there. Otherwise, Spring will not find the repositories classes that it should load up!

查看@EnableNeo4jRepositories 注释。定义的包不存在。尝试定义该包,并注意 Repository 接口基于那里。否则,Spring 将找不到它应该加载的存储库类!