2015-12-24 25 views
4

我正在學習Spring並試圖創建bean並將參數傳遞給它。 我在Spring配置文件中的bean的樣子:當將參數傳遞給Bean時,沒有發現依賴性類型爲[java.lang.String]的限定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 excep和灰:

引起: org.springframework.beans.factory.NoSuchBeanDefinitionException:無類型[java.lang.String中]的 排位豆找到依賴性: 預期至少1豆,其有資格作爲候選自動裝配對於 這種依賴關係。依賴註釋:{}

我做錯了什麼,以及如何解決它?

回答

2

您需要將值傳遞給您的參數,然後只有您可以訪問該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; 
} 

而且在使用下面的代碼

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

但如何改變應用程序執行過程中的路徑訪問該豆你需要訪問它?例如。在應用程序的一個地方,我想創建一個路徑和另一個路徑在其他地方的應用程序的bean。 – May12

+0

另外我已經閱讀了關於PropertyPlaceholderConfigurer,但它不適合我的情況,因爲我想用不同的路徑在程序的不同位置使用bean。可能是spring不允許,因爲在應用程序運行之前設置上下文.... – May12

+2

如果要在運行時創建對象。這是不可能的。由於Spring負責注入,並且在創建對象時需要傳遞依賴關係 –

相關問題