將設定參數(資料庫連線、API 金鑰、功能開關)外部化至 .properties 檔案,是 Java 應用程式「配置與程式碼分離」的基礎做法,便於不同環境部署、敏感資訊管理與動態調整。
Properties 繼承自 Hashtable,專門處理鍵值對,支援 load()/store() 讀寫字元串流,預設編碼為 ISO-8859-1(Java 9+ 可指定 UTF-8)。
原文提到的「是否加斜線」問題,本質是 ClassLoader 資源路徑 vs Class 資源路徑 的差異:
| 呼叫方式 | 路徑基準 | 範例 | 適用情境 |
|---|---|---|---|
ClassLoader.getResourceAsStream("jdbc.properties") | Classpath 根目錄 | src/main/resources/jdbc.properties | 通用、推薦 |
MyClass.class.getResourceAsStream("/jdbc.properties") | Classpath 根目錄 | src/main/resources/jdbc.properties | 需明確從根目錄開始 |
MyClass.class.getResourceAsStream("jdbc.properties") | MyClass 所在套件目錄 | com/test/demo/jdbc.properties | 配置檔與類同包 |
package com.util.config;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
public final class PropertiesUtil {
private static final ConcurrentHashMap CACHE = new ConcurrentHashMap<>();
private PropertiesUtil() {} // 工具類不實例化
/**
* 從 classpath 根目錄載入 properties 檔案(快取)
*/
public static Properties loadFromClasspathRoot(String fileName) {
return CACHE.computeIfAbsent(fileName, name -> {
Properties props = new Properties();
try (InputStream in = PropertiesUtil.class.getClassLoader()
.getResourceAsStream(name)) {
if (in == null) {
throw new IllegalArgumentException("找不到資源檔:" + name);
}
props.load(in);
} catch (IOException e) {
throw new RuntimeException("載入設定檔失敗:" + name, e);
}
return props;
});
}
/**
* 取得字串屬性,支援預設值與 trim
*/
public static String getString(Properties props, String key, String defaultValue) {
String val = props.getProperty(key);
return (val != null) ? val.trim() : defaultValue;
}
/**
* 取得整數屬性
*/
public static int getInt(Properties props, String key, int defaultValue) {
String val = props.getProperty(key);
try {
return (val != null) ? Integer.parseInt(val.trim()) : defaultValue;
} catch (NumberFormatException e) {
return defaultValue;
}
}
// 同理可擴充 getBoolean, getLong, getDuration 等
}
public class DatabaseConfig {
private static final Properties PROPS = PropertiesUtil.loadFromClasspathRoot("jdbc.properties");
public static final String DRIVER = PropertiesUtil.getString(PROPS, "mysql.driverClassName", "com.mysql.cj.jdbc.Driver");
public static final String URL = PropertiesUtil.getString(PROPS, "mysql.url", "");
public static final String USER = PropertiesUtil.getString(PROPS, "mysql.username", "");
public static final String PASS = PropertiesUtil.getString(PROPS, "mysql.password", "");
public static final int POOL_SIZE = PropertiesUtil.getInt(PROPS, "pool.size", 10);
}
new InputStreamReader(in, StandardCharsets.UTF_8) 或 Java 9+ props.load(in) 自動偵測 UTF-8(含 BOM)。src/main/resources 預設會被打包。application-dev.properties、application-prod.properties 搭配 Spring Profile 或啟動參數 -Dspring.profiles.active=prod 切換。FileWatcher 監聽檔案變更並重新載入,或引入 Apollo、Nacos 等配置中心。掌握 ClassLoader 與 Class 兩種資源載入路徑的差異,配合工具類封裝快取、型別轉換、預設值處理,即可建立健壯的配置管理體系。現代專案建議直接使用 Spring @ConfigurationProperties 或配置中心,減少手工維護成本。