首先,有很多解决方案,我已经阅读了很多。但出于某种原因,我没有让它工作。
我正在尝试为我的 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
最佳答案
从META-INF
中取出,放在src/config
中,直接到source中的config包,build后会到/WEB-INF/classes/config/config.properties
和this.getClass().getResourceAsStream("/config/config.properties");
更新
然后我在同一个项目中创建了一个 Service
类,它有一个方法。
public static InputStream getConfigAsInputStream(){
return Service.class.getResourceAsStream("/config/config.properties");
}
这有效..!!
比较你的
关于java - Web 应用程序中的属性文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4814506/