把資料庫位址、第三方服務的 URL、環境開關這類會變動的參數寫死在程式碼裡,是 Java 專案最常見的隱形地雷。一旦環境搬遷,就得重新編譯一次。比較合理的做法,是把這些設定抽到 classpath 底下的 .properties 檔案,再用程式去讀。
整個流程其實只有三步:用 ClassLoader 把檔案當成串流開起來、交給 Properties 載入、最後用 getProperty 取值。
package com.justsy;
import java.io.InputStream;
import java.util.Properties;
public class PropertiesManager {
private String resName = "appstore.properties";
private Properties prop = new Properties();
public PropertiesManager configuration() {
try {
InputStream is = PropertiesManager.class
.getClassLoader()
.getResourceAsStream(resName);
prop.load(is);
if (is != null) {
is.close();
}
} catch (Exception e) {
System.out.println(e + " file " + resName + " not found");
}
return this;
}
public String getPara(String url) {
return prop.getProperty(url);
}
public static void main(String[] args) {
PropertiesManager pm = new PropertiesManager().configuration();
System.out.println(pm.getPara("url"));
}
}
這裡有個順序陷阱值得留意:程式先呼叫 prop.load(is),才判斷 is 是否為 null。真實情況是檔案不存在時 getResourceAsStream 會回傳 null,load 立刻丟出 NullPointerException,那個 null 檢查根本沒機會執行。正確順序應該是先判空、再載入,並且把串流關閉放進 finally 或 try-with-resources 裡。
另一個問題是:每建立一次物件就重讀一次檔案。在設定檔內容幾乎不變的前提下,這是白白浪費的 IO。
把「讀檔」這件事收斂到建構子裡,只跑一次;對外只暴露一個 getInstance()。這樣全應用共用同一份設定,後續取值完全沒有 IO 成本。
package com.justsy.eas.util;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import org.apache.log4j.Logger;
/**
* 讀取配置文件
*/
public class PropertiesReader {
private Logger logger = Logger.getLogger(Properties.class);
private Properties properties;
private static PropertiesReader propertiesReader = new PropertiesReader();
private String resName = "eas.properties";
// 單例私有化構造方法
private PropertiesReader(){
InputStream is = PropertiesReader.class.getClassLoader()
.getResourceAsStream(resName);
properties = new Properties();
try {
properties.load(is);
logger.info("加載配置信息!!");
} catch (IOException e) {
logger.warn("加載配置文件出錯!");
}
}
// 得到 PropertiesReader 的實例
public static PropertiesReader getInstance(){
if(propertiesReader == null){
return new PropertiesReader();
}
return propertiesReader;
}
// 返回所有屬性
public Properties getProperties(){
return this.properties;
}
public static void main(String[] args) {
Properties properties = PropertiesReader.getInstance().getProperties();
System.out.println(properties.getProperty("dbaddr"));
}
}
建構子私有化,外部無法 new,只能透過 getInstance() 取得同一個實例。
設定只載入一次,避開重複 IO,也保證執行期數值一致。
用日誌取代 System.out,正式環境可透過日誌框架的層級設定決定要不要印,而不是硬寫在程式裡。
原始碼中的 getInstance() 其實是「懶漢單例」的破洞版本:因為實例是靜態初始化產生的,propertiesReader 永遠不會是 null,那個 if 分支是死碼;反過來說,如果改成真正的延遲建立,多執行緒下就會有重複 new 的風險,需要加上 synchronized 或改用靜態內部類。此外,串流沒有關閉、載入失敗後仍回傳一個空 Properties(呼叫端會拿到 null 值卻不知道出錯),都是實務上會咬人的細節。改成 try-with-resources,並在失敗時丟出明確的例外,會比吞掉錯誤安全得多。