2011-01-27 42 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