`Properties` 檔案是 Java 專案常見配置載體。J2SE 提供多種載入路徑:檔案系統、類路徑資源、模組系統等。本文整理六種標準方式並給出測試驗證碼。
| 方式 | API | 適用場景 | 路徑範例 |
|---|---|---|---|
| 1. 檔案絕對路徑 | `Files.newInputStream(Path)` | 外部化配置、Docker 掛載 | `/etc/app/config.properties` |
| 2. 類路徑資源 | `ClassLoader.getResourceAsStream()` | 打包在 JAR 內的預設配置 | `com/example/config.properties` |
| 3. 類相對路徑 | `Class.getResourceAsStream()` | 同包配置、測試資源 | `config.properties` (同目錄) |
| 4. ResourceBundle | `ResourceBundle.getBundle()` | 國際化、多環境分層 | `messages` (基名) |
| 5. PropertyResourceBundle | `new PropertyResourceBundle(is)` | 自定義編碼、非標準載入 | InputStream 來源 |
| 6. Spring @PropertySource | `@PropertySource("classpath:...")` | Spring 專案統一配置管理 | SpEL、YAML、加密支援 |
// 方式 2:類路徑(最常用)
try (InputStream is = getClass().getClassLoader()
.getResourceAsStream("config.properties")) {
Properties props = new Properties();
props.load(is); // ISO-8859-1 編碼
String url = props.getProperty("db.url");
}
// 方式 4:ResourceBundle(支援 Locale 分層)
ResourceBundle rb = ResourceBundle.getBundle("messages", Locale.TRADITIONAL_CHINESE);
String title = rb.getString("helloworld.title");@Test void testAllMethods() {
String key = "helloworld.title";
String expected = "Hello World!";
// 1. 絕對路徑
assertEquals(expected, loadByAbsolutePath().getProperty(key));
// 2. 類路徑
assertEquals(expected, loadByClassLoader().getProperty(key));
// 3. 類相對路徑
assertEquals(expected, loadByClassRelative().getProperty(key));
// 4. ResourceBundle
assertEquals(expected, ResourceBundle.getBundle("LocalStrings").getString(key));
// 5. PropertyResourceBundle
assertEquals(expected, new PropertyResourceBundle(is).getString(key));
// 6. Spring 環境需整合測試
}