有時候我們需要把一份設定檔隨函式庫一起打包,而不是外放在部署環境中——例如內建的預設參數、端點位址或功能開關。properties 檔是常見的選擇。
把 engine.properties 放在 src/main/resources 目錄下,Maven 在建置時會自動把它複製到 classes 目錄,最終一併進入 jar 的 root。
關鍵是不能用一般檔案 API 去開它,因為此時它已經不是檔案系統上的檔案,而是 classpath 上的一項資源。正確做法是用 ClassLoader 取得串流:
public class Client {
private final static String NAME = "engine.properties";
public static Map<String, String> load() throws AppEngineException {
InputStream stream = Client.class.getClassLoader().getResourceAsStream(NAME);
...
}
}
路徑要寫 classpath 相對路徑,也就是不含前導斜線的 engine.properties;若寫成 /engine.properties,ClassLoader 版本會找不到資源。若檔案放在子套件(例如 com/example/engine.properties),則要寫完整的 com/example/engine.properties。
讀完務必關閉串流,建議用 try-with-resources 或 finally 收尾,避免在長時間運行的服務中累積檔案描述符。
取得的 InputStream 可能為 null——這通常代表檔案沒有被打進 jar,而非程式邏輯錯誤。排查時可以用 jar tf 或 unzip -l 直接確認資源是否在 jar 的 root。
最後,properties 是純文字格式,不適合存放密碼或金鑰。若確有必要,應在打包前於建置階段加密,再由程式解密,而不是把明文提交進版本控制。