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);
}
}
}
Thread.currentThread().getContextClassLoader() 在 Web 容器 (Tomcat/JBoss)、OSGi、測試框架中都能正確定位類別路徑,避免 ClassLoader.getSystemResource 失效。InputStream,防止洩漏。IllegalStateException,簡化呼叫端處理,保留原始堆疊。createDao 消除重複程式碼,支援任意介面/實作對應。getDeclaredConstructor().newInstance() 支援私有建構子 (需可存取),比 clz.newInstance() (已棄用) 更安全。生產專案建議直接使用 Spring @Configuration + @Bean 或 @ComponentScan,享受依賴注入、生命週期管理、AOP、事務等企業級功能。上述手工工廠適合輕量專案或教學示範。
以 ContextClassLoader + getResourceAsStream + try-with-resources + 反射實例化,構建健壯、可移植的 Properties 驅動工廠。掌握此模式,可快速實現介面與實現解耦,為後續遷移 Spring 奠基。