gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 08:59:19 25 4
gpt4 key购买 nike

我正在练习使用名为 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);
}

}

我收到错误:

Exception in thread "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)

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

Project Structure in 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);
}

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

关于java - 无法使用 Singleton 类在 IntelliJ IDEA 中的属性文件中使用访问属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60285681/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com