2012-03-17 87 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

相关问题