2011-01-27 64 views
3

首先,有很多解决方案,我已经阅读了很多。但由于某种原因,我不明白它的工作原理。web应用中的属性文件

我想为我的webapp外包我的配置数据,这样我就可以在部署后对其进行修改。

这是我的性服务:

public class PropertiesService { 

Properties properties; 
    public PropertiesService() { 
     try { 
     properties = new Properties(); 
     ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); 
     InputStream stream = classLoader.getResourceAsStream("META-INF/config.properties"); 
     properties.load(stream); 
     } catch (Exception e) { 
     e.printStackTrace(); 
     } 
    } 

    public String getHost(){ 
     return properties.getProperty("server_host"); 
    } 

    public String getServerName(){ 
     return properties.getProperty("server_naming"); 
    } 
    } 

调试后,我注意到,可变数据流保持为空!但我不知道为什么-.-

需要帮助:-)

这里的错误日志:

java.lang.NullPointerException 
at java.util.Properties$LineReader.readLine(Properties.java:418) 
at java.util.Properties.load0(Properties.java:337) 
at java.util.Properties.load(Properties.java:325) 

更新

我现在以下:

properties.load(this.getClass().getResourceStream("/config/config.properties")); 

我仍然得到一个NullPointerException

+0

现在没有主角斜杠这应该工作。仔细检查你的类路径,你的部署(是真正存在的文件)和正确的拼写(大小写)。 – mtraut 2011-01-27 09:39:28

回答

7

META-INF取出,把它放在src/config直接以配置包的源,在构建它会去/WEB-INF/classes/config/config.properties

this.getClass().getResourceAsStream("/config/config.properties");

更新 enter image description here

然后我创建了一个Service类在同一个项目中有一个方法。

public static InputStream getConfigAsInputStream(){ 
    return Service.class.getResourceAsStream("/config/config.properties"); 
} 

This works works .. !!

比较你的

+0

也许你应该补充说,你不使用类加载器 - 你使用servlet的上下文... – mtraut 2011-01-27 09:24:42