利用 java.util.ResourceBundle 實現線程安全的單例模式,便於全局獲取配置屬性。
import java.util.ResourceBundle;
public class ConfigHelper {
private static ConfigHelper instance;
private ConfigHelper() {}
public static ConfigHelper getInstance() {
if (instance == null) {
synchronized (ConfigHelper.class) {
if (instance == null) {
instance = new ConfigHelper();
}
}
}
return instance;
}
public ResourceBundle getConfigResource(String propertyName) {
return ResourceBundle.getBundle(propertyName.trim());
}
}
將 config.properties 放置在 classpath 下(如 src/main/resources):
# CPU 權重
cpuWeight=0.5
# 內存權重
memoryWeight=0.3
# 磁盤權重
diskWeight=0.2
String cpuWeight = ConfigHelper.getInstance()
.getConfigResource("config")
.getString("cpuWeight");
此工具類簡潔高效,適合中小型項目快速接入配置管理。