簡體   English   中英

AWS Lambda Java如何讀取屬性文件

[英]AWS Lambda Java how to read properties file

我嘗試將屬性從文件加載到Properties類中。 我希望該解決方案能起作用: 如何從AWS Lambda Java中的類路徑加載屬性文件

我有一個很少使用靜態方法的類,我想將其用作Config持有人。 里面有這條線

final InputStream inputStream = 
Config.class.getClass().getResourceAsStream("/application-main.properties");

並且它總是返回null。 我下載了Lambda使用的zip軟件包,該文件位於root用戶內部。 仍然不起作用。

有人有類似的問題嗎?

編輯:配置文件在這里:

project
└───src
│   └───main
│      └───resources
│            application-main.properties

編輯:我的“臨時”解決方法如下所示:

// LOAD PROPS FROM CLASSPATH...
try (InputStream is = Config.class.getResourceAsStream(fileName)) {
        PROPS.load(is);
    } catch (IOException|NullPointerException exc) {
        // ...OR FROM FILESYSTEM
        File file = new File(fileName);
        try (InputStream is = new FileInputStream(file)) {
            PROPS.load(is);
        } catch (IOException exc2) {
            throw new RuntimeException("Could not read properties file.");
        }
    }

在測試期間,它從類路徑讀取,在AWS Lambda運行時中部署后,它使用文件系統。 要標識我使用的env變量文件:

fileName = System.getenv("LAMBDA_TASK_ROOT")  + "/application-main.properties";

但是我寧願只使用classpath而不解決此問題。

當您要加載屬性文件時,可以使用ResourceBundle加載屬性。

String version = ResourceBundle.getBundle("application-main").getString("version");

它與作為InputStream加載文件不同,但這對我InputStream

我有一個簡單的Hello-World Lambda,它從github上的屬性文件讀取當前版本。

假設src / main / resources / config.properties

File file = new File(classLoader.getResource("resources/config.properties").getFile());
FileInputStream fileInput = new FileInputStream(file);
prop.load(fileInput);

假設您具有以下文件夾結構:

 project └───src │ └───main │ └───resources │ config.properties 

還有您的Lambda處理程序:

 ClassLoader loader = Config.class.getClassLoader(); InputStream input = loader.getResourceAsStream("config.properties"); 

可能行得通...

如果src / main / resource包中有一個.properties文件,請嘗試以下操作:

protected static Properties readPropertiesFile() {
    ClassLoader classLoader = Utils.class.getClassLoader();
    try {
        InputStream is = classLoader.getResourceAsStream("PropertiesFile.properties");
        Properties prop = new Properties();
        prop.load(is);
        return prop;
    } catch (Exception e) {
        return null;
    }
}

您可以通過以下方式調用它:

Properties _dbProperties = Utils.readPropertiesFile();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM