繁体   English   中英

无法使用 Singleton 类在 IntelliJ IDEA 中使用属性文件中的访问属性

[英]Unable to use access properties from Properties file in IntelliJ IDEA using Singleton class

我正在练习使用名为 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 parameter is null at java.base/java.util.Objects.requireNonNull(Objects.java:247) at java.base/java.util.Properties.load(Properties. java:404) at in.net.sudhir.evernote.client.batchjob.PropertyLoader.(PropertyLoader.java:16) at in.net.sudhir.evernote.client.batchjob.PropertyLoader.getInstance(PropertyLoader.java:23) at in.net.sudhir.evernote.client.batchjob.EvernoteClient.(EvernoteClient.java:51) at in.net.sudhir.evernote.client.batchjob.BatchProcess.main(BatchProcess.java:33)

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

IntelliJ IDEA 中的项目结构

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM