萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Java Properties 配置檔讀取完整實作:Thread.currentThread().getContextClassLoader() 最佳實務

配置檔 beans.properties

articleDao=cn.com.leadfar.cms.backend.dao.impl.ArticleDaoImpl
channelDao=cn.com.leadfar.cms.backend.dao.impl.ChannelDaoImpl

工廠類完整實作

package cn.com.leadfar.cms.utils;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import cn.com.leadfar.cms.backend.dao.ArticleDao;
import cn.com.leadfar.cms.backend.dao.ChannelDao;

public class PropertiesBeanFactory implements BeanFactory {

    private final Properties props = new Properties();

    public PropertiesBeanFactory() {
        // 1. 取得執行緒上下文類別載入器 (支援 Web 容器、OSGi、單元測試)
        ClassLoader cl = Thread.currentThread().getContextClassLoader();
        // 2. 以資源流形式讀取 classpath 下的 properties 檔
        try (InputStream is = cl.getResourceAsStream("beans.properties")) {
            if (is == null) {
                throw new IllegalStateException("classpath 下找不到 beans.properties");
            }
            props.load(is);
        } catch (IOException e) {
            throw new IllegalStateException("載入 beans.properties 失敗", e);
        }
    }

    public ArticleDao getArticleDao() {
        return createDao("articleDao", ArticleDao.class);
    }

    public ChannelDao getChannelDao() {
        return createDao("channelDao", ChannelDao.class);
    }

    @SuppressWarnings("unchecked")
    private  T createDao(String key, Class iface) {
        String className = props.getProperty(key);
        if (className == null || className.trim().isEmpty()) {
            throw new IllegalStateException("配置缺少鍵: " + key);
        }
        try {
            Class clz = Class.forName(className, true, 
                            Thread.currentThread().getContextClassLoader());
            return (T) clz.getDeclaredConstructor().newInstance();
        } catch (ReflectiveOperationException e) {
            throw new IllegalStateException("實例化 " + className + " 失敗", e);
        }
    }
}

關鍵最佳實務解析

  1. 使用 Context ClassLoader:Thread.currentThread().getContextClassLoader() 在 Web 容器 (Tomcat/JBoss)、OSGi、測試框架中都能正確定位類別路徑,避免 ClassLoader.getSystemResource 失效。
  2. try-with-resources:JDK 7+ 自動關閉 InputStream,防止洩漏。
  3. 異常轉換:將受檢異常包裝為非受檢 IllegalStateException,簡化呼叫端處理,保留原始堆疊。
  4. 泛型輔助方法:createDao 消除重複程式碼,支援任意介面/實作對應。
  5. 反射實例化:getDeclaredConstructor().newInstance() 支援私有建構子 (需可存取),比 clz.newInstance() (已棄用) 更安全。

Spring 整合替代方案

生產專案建議直接使用 Spring @Configuration + @Bean 或 @ComponentScan,享受依賴注入、生命週期管理、AOP、事務等企業級功能。上述手工工廠適合輕量專案或教學示範。

結語

以 ContextClassLoader + getResourceAsStream + try-with-resources + 反射實例化,構建健壯、可移植的 Properties 驅動工廠。掌握此模式,可快速實現介面與實現解耦,為後續遷移 Spring 奠基。

copyright © 萬盛學電腦網 all rights reserved