Load Properties File in Singleton Class

六月ゝ 毕业季﹏ 提交于 2019-12-02 12:27:44

问题


I have seen this posted a couple of times and tried a few of the suggestions with no success (so far). I have a maven project and my properties file in on the following path:

[project]/src/main/reources/META_INF/testing.properties

I am trying to load it in a Singleton class to access the properties by key

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);
    }

}

but I am getting a NullPointerError when this runs... I have done everything I can think of to the path, but it won't find/load the file.

Any ideas?

Stacktrace:

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)

回答1:


You should instantiate your Properties object. Also you should load the resource file with the path starting with /META-INF:

properties = new Properties();
properties.load(getClass().getResourceAsStream("/META-INF/testing.properties"));



回答2:


properties is null... you must first instantiate it.. then load it.



来源:https://stackoverflow.com/questions/24962265/load-properties-file-in-singleton-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!