單例模式:
public class ConfigManager {
private static ConfigManager configManager = null;
private Properties properties = new Properties();
private ConfigManager() {
try {
properties.load(new FileInputStream("src/data.properties"));
} catch (IOException e) {
e.printStackTrace();
}
}
public static ConfigManager newInstance() {
if (configManager == null) {
configManager = new ConfigManager();
}
return configManager;
}
public String getValue(String key) {
return properties.get(key).toString();
}
}
靜態代碼塊方式:
public class ConfigManager1 {
private static String name = null;
private static String pwd = null;
private static String driver = null;
private static String url = null;
static {
Properties properties = new Properties();
try {
properties.load(new FileInputStream("src/data.properties"));
name = properties.getProperty("name");
pwd = properties.getProperty("pwd");
driver = properties.getProperty("driver");
url = properties.getProperty("url");
} catch (IOException e) {
e.printStackTrace();
}
}
public static String getName() {
return name;
}
public static String getPwd() {
return pwd;
}
public static String getDriver() {
return driver;
}
public static String getUrl() {
return url;
}
}