Web应用程序中的属性文件

时间:2011-01-27 09:18:13

标签: java configuration properties

首先,有很多解决方案,我已经阅读了很多解决方案。但由于某种原因,我没有让它发挥作用。

我正在尝试将我的配置数据外包给我的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

1 个答案:

答案 0 :(得分: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");
}

这有效.. !!

比较你的