@pastqing
2015-01-20T17:10:14.000000Z
字数 2507
阅读 5565
java
public enum ConfigReader {
SDUST;
private volatile Properties configuration = new Properties();
public void init() {
InputStream is = this.getClass().getResourceAsStream("db-configuration.xml");
if( is != null ) {
this.configuration.clear();
try {
this.configuration.loadFromXML(is);
//this.configuration.load(is);
} catch (InvalidPropertiesFormatException e) {
System.out.println("Properties 格式不对");
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally { //无论异常是否发生, 都关闭
try {
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public String getConfigurationValue(String key) {
return this.configuration.getProperty(key);
}
/**
* 常量类
* @author su
*/
public final class Contants {
private Contants() {
}
/**
* 配置文件常量
*/
public final static class Configuration {
private Configuration() {
}
public static final Map<String, Configurations> configMap = new HashMap<String, Configurations>();
private static Configurations sql, mysql;
public static final void init() {
/**
* 构造
*/
sql = new Configurations();
mysql = new Configurations();
//mysql
mysql.setDb_driver(ConfigReader.SDUST.getConfigurationValue("MYSQL_DRIVER"));
mysql.setDb_path(ConfigReader.SDUST.getConfigurationValue("MYSQL_URL"));
mysql.setDb_name(ConfigReader.SDUST.getConfigurationValue("MYSQL_USERNAME"));
mysql.setDb_pass(ConfigReader.SDUST.getConfigurationValue("MYSQL_PASSWORD"));
//sqlserver
sql.setDb_driver(ConfigReader.SDUST.getConfigurationValue("SQL_DRIVER"));
sql.setDb_path(ConfigReader.SDUST.getConfigurationValue("SQL_URL"));
sql.setDb_name(ConfigReader.SDUST.getConfigurationValue("SQL_USERNAME"));
sql.setDb_pass(ConfigReader.SDUST.getConfigurationValue("SQL_PASSWORD"));
//
System.out.println("put map");
configMap.put("sql", sql);
configMap.put("mysql", mysql);
}
}
}
public Connection getConnection(String type) {
//根据传入的类型做判断, 来选择调用常量类中configMap里面的value
Connection DBConn = null;
Contants.Configuration.init();
//使用type别忘记做各种判断
Configurations config = configMap.get(type);
//下面就是连接数据库的各种操作了, 此处省略
...
...
}
感觉利用java枚举的特性写单例模式还是比较新颖的, 也比较安全。故记录之。