首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 綜合教學

Java 讀取配置文件的多種姿勢:Spring、Apache Commons Configuration 與純 JDK 實現對比

     編輯:Java 綜合教學

Java 讀取配置文件的多種姿勢:從框架到純 JDK 實現

前言:為什麼需要配置文件?

無論專案大小,資料庫連線、環境參數、第三方服務地址等資訊絕不能硬編碼在程式中。硬編碼弊端:

  • 配置變更需重新編譯打包部署
  • 開發與運維職責無法分離
  • 配置分散各處,難以集中管理

主流配置格式:.properties(鍵值對)、.xml(複雜結構)、.yaml/.yml(現代化、層次清晰)。


方案一:Spring ResourceLoader 抽象

Spring 提供統一資源載入抽象 `ResourceLoader`,預設實現 `DefaultResourceLoader` 支援多種路徑前綴:

  • `classpath:` - 類路徑資源
  • `file:` - 檔案系統絕對路徑
  • `http:` / `https:` - 網路資源
  • `/` - 絕對路徑或 ServletContext 相對路徑

核心實現邏輯(簡化版)

public Resource getResource(String location) {
    // 1. 協議解析器優先嘗試解析
    for (ProtocolResolver resolver : protocolResolvers) {
        Resource r = resolver.resolve(location, this);
        if (r != null) return r;
    }
    // 2. 內建協議處理
    if (location.startsWith("/")) return getResourceByPath(location);
    if (location.startsWith("classpath:")) return new ClassPathResource(...);
    try {
        return new UrlResource(new URL(location));
    } catch (MalformedURLException e) {
        return getResourceByPath(location);  // 退回檔案路徑
    }
}

使用範例



方案二:Apache Commons Configuration

專門處理配置的輕量庫(~400KB),設計精良,支援多種格式與來源合併。

兩行代碼搞定

PropertiesConfiguration config = new PropertiesConfiguration("log4j.properties");
String value = config.getString("log4j.appender.file");

核心載入邏輯

public void load(String fileName) throws ConfigurationException {
    URL url = ConfigurationUtils.locate(fileSystem, basePath, fileName);
    if (url == null) throw new ConfigurationException("Cannot locate: " + fileName);
    load(url);
}

進階特性

  • 自動重載(`setReloadingStrategy`)
  • 多配置來源合併(`CombinedConfiguration`)
  • 型別安全獲取(`getInt`、`getBoolean`、`getList`)
  • 變數插值(`${env.VAR}`、`${sys:prop}`)

方案三:純 JDK 手寫實現(零依賴)

若專案極簡、不想引入第三方 JAR,或追求極致輕量,JDK 原生 API 完全足夠。

核心三行代碼

// 方式 1:類載入器獲取 URL(推薦,支援 classpath)
URL resource = Thread.currentThread().getContextClassLoader().getResource("config.properties");
Properties props = new Properties();
props.load(resource.openStream());
String value = props.getProperty("key");

方式 2:檔案系統路徑讀取

String url = MyClass.class.getResource("").getPath().replaceAll("%20", " ");
String path = url.substring(0, url.indexOf("classes")) + "config.properties";
try (InputStream is = new FileInputStream(path);
     BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"))) {
    Properties props = new Properties();
    props.load(br);
    String value = props.getProperty("key");
}

方案對比總結

維度Spring ResourceLoaderApache Commons Configuration純 JDK
依賴大小Spring Core (~1.5MB)~400KB0 KB
路徑解析能力極強(多協議)中等基礎
型別轉換需手動內建豐富需手動
熱重載需額外配置內建支援需自行實現
適用場景Spring 專案非 Spring/獨立模組極簡專案/工具類

實戰封裝:通用配置載入工具類(零依賴)

public final class ConfigUtil {
    private static final Properties PROPS = new Properties();
    private static final String DEFAULT_CONFIG = "application.properties";
    private static volatile boolean initialized = false;
    
    static {
        load(DEFAULT_CONFIG);
    }
    
    public static synchronized void load(String configPath) {
        if (initialized) return;
        try (InputStream is = Thread.currentThread()
                .getContextClassLoader().getResourceAsStream(configPath)) {
            if (is == null) {
                throw new IllegalStateException("Config not found: " + configPath);
            }
            PROPS.load(new InputStreamReader(is, StandardCharsets.UTF_8));
            initialized = true;
        } catch (IOException e) {
            throw new ExceptionInInitializerError(e);
        }
    }
    
    public static String get(String key) {
        return PROPS.getProperty(key);
    }
    
    public static String get(String key, String defaultValue) {
        return PROPS.getProperty(key, defaultValue);
    }
    
    public static int getInt(String key, int defaultValue) {
        String v = PROPS.getProperty(key);
        return v != null ? Integer.parseInt(v) : defaultValue;
    }
    
    public static boolean getBoolean(String key, boolean defaultValue) {
        String v = PROPS.getProperty(key);
        return v != null ? Boolean.parseBoolean(v) : defaultValue;
    }
}

最佳實踐建議

  1. Spring 專案:直接用 `@Value`、`@ConfigurationProperties` 或 `Environment`,無需手寫
  2. 微服務/雲原生:配合 Spring Cloud Config、Nacos、Apollo 等配置中心
  3. 獨立工具/舊專案:Apache Commons Configuration 性價比最高
  4. 極簡場景:複製上方 `ConfigUtil` 即用,編譯後 < 5KB
  5. 編碼統一:強制指定 UTF-8,避免中文亂碼

配置管理看似簡單,實則關係專案可維護性與部署靈活性。選對工具,事半功倍。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved