在将参数传递给Bean时,没有找到类型[java.lang.String]的限定bean用于依赖项

May*_*y12 5 java spring

我正在研究Spring并尝试创建bean并将参数传递给它.Spring配置文件中的bean看起来像:

@Bean
@Scope("prototype")
public InputFile inputFile (String path)
{
    InputFile inputFile = new InputFile();
    inputFile.setPath(path);
    return inputFile;
}
Run Code Online (Sandbox Code Playgroud)

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

在主要方法中我有:

InputFile inputFile = (InputFile) ctx.getBean("inputFile", "C:\\");
Run Code Online (Sandbox Code Playgroud)

C:\\ - 是我试图传递的参数.

我运行应用程序并收到root异常:

org.springframework.beans.factory.NoSuchBeanDefinitionException:通过引起[java.lang.String中]找到依赖性否类型的排位豆:预期至少1种豆,其有资格作为自动装配候选这种依赖性.依赖注释:{}

我做错了什么以及如何解决它?

Viv*_*ngh 5

您需要将值传递给您的参数,然后才能访问该bean.这是Exception中给出的消息.

在方法声明上方使用@Value注释并将值传递给它.

@Bean
@Scope("prototype")
@Value("\\path\\to\\the\\input\\file")
public InputFile inputFile (String path)
{
    InputFile inputFile = new InputFile();
    inputFile.setPath(path);
    return inputFile;
}
Run Code Online (Sandbox Code Playgroud)

在访问此bean时,您需要使用以下代码访问它

InputFile inputFile = (InputFile) ctx.getBean("inputFile");
Run Code Online (Sandbox Code Playgroud)

  • 如果要在运行时创建对象.这是不可能的.由于Spring负责注入,因此您需要在创建对象时传递依赖项 (2认同)