簡體   English   中英

將參數傳遞給Bean時,沒有找到依賴項的類型為[java.lang.String]的合格Bean

[英]No qualifying bean of type [java.lang.String] found for dependency when pass parameter to the Bean

我正在研究Spring並嘗試創建bean並將參數傳遞給它。 我的Spring配置文件中的bean如下所示:

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

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;
    }
}

在主要方法中,我有:

InputFile inputFile = (InputFile) ctx.getBean("inputFile", "C:\\");

C:\\\\ -是我要傳遞的參數。

我運行應用程序並收到root異常:

由以下原因導致:org.springframework.beans.factory.NoSuchBeanDefinitionException:未找到類型為[java.lang.String]的合格Bean作為依賴項:至少應有1個有資格作為此依賴項的自動裝配候選的bean。 依賴注釋:{}

我做錯了什么以及如何解決?

您需要將值傳遞給參數,然后只有您才能訪問Bean。 這就是異常中給出的消息。

在方法聲明上方使用@Value批注,並將值傳遞給它。

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

另外,在訪問此bean時,您需要使用以下代碼訪問它

InputFile inputFile = (InputFile) ctx.getBean("inputFile");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM