以数据库的属性为例,我们要访问数据库就必须告诉jdk数据库的驱动,数据库的名称,用户名,密码等,如果把这些东西都写在程序里,势必会影响程序的重用性,万一数据库信息变化了,我们就必须埋头去搜啊改啊的,但如果把这些配置方面的信息写在一个.properties的文件中,系统初始化的时候将这个文件中的内容读入到系统中使用,以后就是这些信息变化了,我们只要改动.properties文件就可以了,是不是很方便呢?
呵呵,菜鸟们enjoy:)
从属性文件中读配置属性如下
//系统配置属性
protected static String SYSTEM_CONFIG =
"SystemConfig.properties";
protected static String DB_DRIVER_NAME = "DBDriverName";
protected static String DB_URL = "DBURL";
protected static String DB_USER = "DBUser";
protected static String DB_USERPASS = "DBUserPass";
private void initialze(HttpSession session) throws Exception {
Properties properties = new Properties();
InputStream InputStream = this.getClass().getClassLoader().
getResourceAsStream(SYSTEM_CONFIG);
properties.load(InputStream);
DBConnection.dbDriverName = (String) session.getAttribute(DB_DRIVER_NAME);
if (DBConnection.dbDriverName == null ||
DBConnection.dbDriverName.equals("")) {
DBConnection.dbDriverName = properties.getProperty(DB_DRIVER_NAME).trim();
if (DBConnection.dbDriverName == null ||
DBConnection.dbDriverName.equals("")) {
throw (new Exception(DB_DRIVER_NAME + "的值为空。"));
}
}
DBConnection.dbURL = (String) session.getAttribute(DB_URL);
if (DBConnection.dbURL == null || DBConnection.dbURL.equals("")) {
DBConnection.dbURL = properties.getProperty(DB_URL).trim();
if (DBConnection.dbURL == null || DBConnection.dbURL.equals("")) {
throw (new Exception(DB_URL + " 的值为空。"));
}
}
DBConnection.dbUserID = (String) session.getAttribute(DB_USER);
if (DBConnection.dbUserID == null || DBConnection.dbUserID.equals("")) {
DBConnection.dbUserID = properties.getProperty(DB_USER).trim();
if (DBConnection.dbUserID == null || DBConnection.dbUserID.equals("")) {
throw (new Exception(DB_USER + " 的值为空。"));
}
}
DBConnection.dbUserPass = (String) session.getAttribute(DB_USERPASS);
if (DBConnection.dbUserPass == null || DBConnection.dbUserPass.equals("")) {
DBConnection.dbUserPass = properties.getProperty(DB_USERPASS).trim();
if (DBConnection.dbUserPass == null || DBConnection.dbUserPass.equals("")) {
throw (new Exception(DB_USERPASS + " 的值为空。"));
}
}