在单例类中加载属性文件

Tho*_*rer 4 java properties classpath maven

我已经看到这个帖子发布了几次,并尝试了一些建议但没有成功(到目前为止)。我在以下路径中有一个 Maven 项目和我的属性文件:

[project]/src/main/reources/META_INF/testing.properties
Run Code Online (Sandbox Code Playgroud)

我正在尝试将它加载到 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);
    }

}
Run Code Online (Sandbox Code Playgroud)

但是当它运行时我得到了一个 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)
Run Code Online (Sandbox Code Playgroud)

man*_*uti 5

你应该实例化你的Properties对象。此外,您应该加载以以下开头的路径的资源文件/META-INF

properties = new Properties();
properties.load(getClass().getResourceAsStream("/META-INF/testing.properties"));
Run Code Online (Sandbox Code Playgroud)