在Singleton类中加载属性文件

在Singleton类中加载属性文件

本文介绍了在Singleton类中加载属性文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看过几次,并尝试了一些建议但没有成功(到目前为止)。我有一个maven项目,我的属性文件位于以下路径:

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

我试图在Singleton类中加载它以通过键访问属性

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

}

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

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.

任何想法?

Stacktrace:

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)


推荐答案

你应该实例化你的属性对象。您还应该加载资源文件,其路径以 / META-INF 开头:

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

这篇关于在Singleton类中加载属性文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 01:48