将参数传递给 Bean 时,找不到类型为 [java.lang.String] 的符合条件的 bean 依赖项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34450028/
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
No qualifying bean of type [java.lang.String] found for dependency when pass parameter to the Bean
提问by May12
I am studing Spring and trying to create bean and pass parameter to it. My bean in Spring configuration file looks like:
我正在研究 Spring 并尝试创建 bean 并将参数传递给它。我在 Spring 配置文件中的 bean 如下所示:
@Bean
@Scope("prototype")
public InputFile inputFile (String path)
{
InputFile inputFile = new InputFile();
inputFile.setPath(path);
return inputFile;
}
InputFile class is:
InputFile 类是:
public class InputFile {
String path = null;
public InputFile(String path) {
this.path = path;
}
public InputFile() {
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
}
and in main method i have:
在主要方法中,我有:
InputFile inputFile = (InputFile) ctx.getBean("inputFile", "C:\");
C:\\
- is a parameter which i am trying to pass in.
C:\\
- 是我试图传入的参数。
I run application and receive root exception:
我运行应用程序并收到根异常:
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [java.lang.String] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
引起:org.springframework.beans.factory.NoSuchBeanDefinitionException:找不到类型为 [java.lang.String] 的合格 bean 依赖项:预期至少有 1 个 bean 有资格作为此依赖项的自动装配候选者。依赖注释:{}
What i did wrong and how to fix it?
我做错了什么以及如何解决?
采纳答案by Vivek Singh
You need to pass a value to your parameter then only you can access the bean. This is what the message given in the Exception.
您需要将一个值传递给您的参数,然后只有您才能访问该 bean。这就是异常中给出的消息。
Use @Value annotation above the method declaration and pass a value to it.
在方法声明上方使用@Value 注释并将值传递给它。
@Bean
@Scope("prototype")
@Value("\path\to\the\input\file")
public InputFile inputFile (String path)
{
InputFile inputFile = new InputFile();
inputFile.setPath(path);
return inputFile;
}
Also while accessing this bean you need to access it using the below code
此外,在访问此 bean 时,您需要使用以下代码访问它
InputFile inputFile = (InputFile) ctx.getBean("inputFile");