簡體   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