Java 在单例类中加载属性文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24962265/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 16:00:10  来源:igfitidea点击:

Load Properties File in Singleton Class

javamavenpropertiesclasspath

提问by Thomas Moorer

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:

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

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

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

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

}

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.

但是当它运行时我得到一个 NullPointerError ......我已经做了我能想到的所有路径,但它不会找到/加载文件。

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)

采纳答案by M Anouti

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

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

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

回答by T McKeown

propertiesis null... you must first instantiate it.. then load it.

properties为空...您必须先实例化它...然后加载它。