[英]Load Properties File in Singleton Class
我已经看过几次,并尝试了一些建议,但都没有成功(到目前为止)。 我在以下路径上有一个maven项目和属性文件:
[project]/src/main/reources/META_INF/testing.properties
我试图将其加载到Singleton类中以通过键访问属性
public class TestDataProperties {
private static TestDataProperties instance = null;
private Properties properties;
protected TestDataProperties() throws IOException{
properties = new Properties();
properties.load(getClass().getResourceAsStream("testing.properties"));
}
public static TestDataProperties getInstance() {
if(instance == null) {
try {
instance = new TestDataProperties();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
return instance;
}
public String getValue(String key) {
return properties.getProperty(key);
}
}
但是我在运行时遇到了NullPointerError的问题。我已经完成了所有可以想到的操作,但是无法找到/加载文件。
有任何想法吗?
堆栈跟踪:
Exception in thread "main" java.lang.NullPointerException
at java.util.Properties$LineReader.readLine(Properties.java:434)
at java.util.Properties.load0(Properties.java:353)
at java.util.Properties.load(Properties.java:341)
您应该实例化Properties
对象。 另外,您应该使用/META-INF
开头的路径加载资源文件:
properties = new Properties();
properties.load(getClass().getResourceAsStream("/META-INF/testing.properties"));
properties
为null ...您必须首先实例化它..然后加载它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.