【问题标题】:Unable to use access properties from Properties file in IntelliJ IDEA using Singleton class无法使用单例类在 IntelliJ IDEA 中使用属性文件中的访问属性
【发布时间】:2020-02-18 16:43:38
【问题描述】:

我正在练习使用一个名为 PropertyLoader 的单例类从属性文件中访问属性,但是我的 maven 项目无法在资源中找到该文件并给出空指针异常。

这是课程代码。

import java.io.IOException;
import java.util.Properties;
import org.apache.log4j.Logger;

public class PropertyLoader {
    private static PropertyLoader instance = null;
    private Properties properties;
    private final static Logger LOGGER = Logger.getLogger(PropertyLoader.class.getName());


    protected PropertyLoader() throws IOException {
        //TODO: Fix problem with loading properties file below
        properties = new Properties();
        properties.load(PropertyLoader.class.getResourceAsStream("app.properties"));

    }

    public static PropertyLoader getInstance() {
        if(instance == null) {
            try {
                instance = new PropertyLoader();
            } catch (IOException ioe) {
                LOGGER.error("Error Occurred while creating Property Loader instance: " + ioe.getMessage());
            }
        }
        return instance;
    }

    public String getValue(String key) {
        LOGGER.info("Getting property value for: " + key);
        return properties.getProperty(key);
    }

}

我得到的错误:

线程“main”中的异常 java.lang.NullPointerException: inStream 参数为空 java.base/java.util.Objects.requireNonNull(Objects.java:247) 在 java.base/java.util.Properties.load(Properties.java:404) 在 in.net.sudhir.evernote.client.batchjob.PropertyLoader.(PropertyLoader.java:16) 在 in.net.sudhir.evernote.client.batchjob.PropertyLoader.getInstance(PropertyLoader.java:23) 在 in.net.sudhir.evernote.client.batchjob.EvernoteClient.(EvernoteClient.java:51) 在 in.net.sudhir.evernote.client.batchjob.BatchProcess.main(BatchProcess.java:33)

这是项目结构的屏幕截图。

Project Structure in IntelliJ IDEA

【问题讨论】:

    标签: java intellij-idea properties singleton


    【解决方案1】:
    properties = new Properties();
    
    try(InputStream inputStream = PropertyLoader.class.getClassLoader().getResourceAsStream("app.properties")) {
        if(inputStream == null)
            throw new FileNotFoundException("File not found in classpath");
    
        properties.load(inputStream);
    }
    

    注意:在构造函数中进行计算是不好的做法。最好创建一些加载资源文件的方法。

    【讨论】:

    • 谢谢,但你能解释一下我的代码和你的代码有什么区别吗?两者似乎都是一样的,这是因为我在构造函数中使用了它吗?
    • PropertyLoader.class.getClassLoader()
    • 明白谢谢
    猜你喜欢
    • 2014-03-26
    • 2017-12-14
    • 2021-10-26
    • 1970-01-01
    • 1970-01-01
    • 2018-11-07
    • 2012-12-07
    • 2016-08-17
    • 1970-01-01
    相关资源
    最近更新 更多