2012-03-17 88 views
2

我有一個屬性文件,我現在有這個文件夾中:我應該在哪裏放置我的屬性文件進行測試?

/src/webapp/WEB-INF/classes/my.properties 

我使用加載它:

ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); 
InputStream is = classLoader.getResourceAsStream("/my.properties"); 

Properties props = new Properties(); 

try { 
    props.load(is); 
} catch (IOException e) { 
    e.printStackTrace(); 
} 

String test = props.getProperty("test"); 

現在能正常工作在我的Spring MVC應用程序。

但是當我爲此創建一個測試時,它失敗了,我假設因爲應用程序加載它的方式不使用web-inf/classes,因爲它只是一個類而不是彈簧web應用程序。

那麼,我把我的屬性文件,以便當我的junit測試運行時,屬性文件被拾起?

此外,對於我的web應用程序,除了/ web-inf/classes之外,還有哪些其他文件夾位於默認類路徑中?

+1

我相信你的路徑是:'/ src目錄/ web應用/ WEB-INF /班/ my.properties' – 2012-03-17 14:38:46

回答

5

如果您將my.properties放在/src/test/resources之下,它將作爲您測試的常規資源提供。

0

通常我把屬性文件直接放在src文件夾中。

1

由於類加載器在應用程序的根目錄中啓動,我將刪除classLoader.getResourceAsStream("/my.properties");中的路徑(/)。保持文件在相同的位置。然後換

String filename = "my.properties"; 
InputStream is = classLoader.getResourceAsStream(filename); //for web-app 
if(is == null) 
    is = new FileInputStream (filename);  //for testing 
+0

,但怎麼就正在與web應用程序的/?困惑? – Blankman 2012-03-17 21:29:04

+0

類加載器已經在根中搜索,所以/沒有任何區別。在另一個,如果你想嘗試 'class.getResourceAsStream(filename)'在類中搜索同一個包(文件夾)中的資源,所以在這種情況下,如果文件位於根目錄中,那麼/就是必需的。 – Kennet 2012-03-18 18:18:30

相關問題