Java 應用中屬性檔的讀取場景多樣:classpath 內嵌配置、外部檔案系統配置、Spring 環境整合、多環境隔離等。不同場景下最佳讀取方式不同,本文系統梳理 7 種主流方式,並給出選型建議。
Properties props = new Properties();
try (InputStream in = new BufferedInputStream(new FileInputStream("/opt/config/app.properties"))) {
props.load(in);
}
String value = props.getProperty("key");
// 僅支援 classpath 下的 .properties 檔,檔名不含副檔名
ResourceBundle bundle = ResourceBundle.getBundle("config.app", Locale.getDefault());
String value = bundle.getString("key");
try (InputStream in = new BufferedInputStream(new FileInputStream("app.properties"))) {
ResourceBundle bundle = new PropertyResourceBundle(in);
String value = bundle.getString("key");
}
// 相對當前類所在包路徑
try (InputStream in = MyClass.class.getResourceAsStream("config.properties")) {
Properties props = new Properties();
props.load(in);
}
/ 開頭 = 相對當前類包路徑;以 / 開頭 = 相對 classpath 根目錄// 推薦:統一從 classpath 根目錄讀取
try (InputStream in = MyClass.class.getClassLoader().getResourceAsStream("config/app.properties")) {
Properties props = new Properties();
props.load(in);
}
try (InputStream in = ClassLoader.getSystemResourceAsStream("config.properties")) {
Properties props = new Properties();
props.load(in);
}
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-configuration2</artifactId>
<version>2.10.1</version>
</dependency>
// 程式碼
PropertiesConfiguration config = new PropertiesConfiguration("test.properties");
String value = config.getProperty("key").toString();
| 場景 | 推薦方式 | 理由 |
|---|---|---|
| Spring Boot 專案 | @Value / @ConfigurationProperties | 框架原生支援,自動綁定、驗證、熱更新 |
| 獨立 Java 應用,配置在 classpath | 方式五 | 標準、無依賴、路徑穩定 |
| 配置檔在檔案系統外部 | 方式一 + 路徑參數化 | 支援外掛式部署 |
| 國際化訊息 | 方式二 | JDK 內建、Locale 整合 |
| 需熱更新、複雜類型、多源合併 | 方式七 | 功能最完整 |