采用singleton模式,利用Apache Digester读取数据库驱动名、URL、用户名、密码
tb.xml
--------------------
<?xml version="1.0" encoding="ISO-8859-1"?>
<tb>
<database>
<driver>com.mysql.jdbc.Driver</driver>
<url>jdbc:mysql://127.0.0.1:3306/tb?autoReconnect=ture&useUnicode=true&characterEncoding=UTF-8</url>
<user>user</user>
<password>password</password>
</database>
</tb>
config.java
--------------------
package com.terac.board;
import org.apache.commons.digester.Digester;
import org.xml.sax.SAXException;
import java.io.IOException;
import java.io.InputStream;
public class Config {
private String databaseDriver;
private String databaseUrl;
private String databaseUser;
private String databasePassword;
private final static Config instance = new Config();
public static Config getInstance() {
return instance;
}
private Config() {
Digester digester = new Digester();
digester.push(this);
digester.addCallMethod("tb/database/driver", "setDatabaseDriver", 0);
digester.addCallMethod("tb/database/url", "setDatabaseUrl", 0);
digester.addCallMethod("tb/database/user", "setDatabaseUser", 0);
digester.addCallMethod("tb/database/password", "setDatabasePassword", 0);
InputStream is = null;
try {
is = this.getClass().getClassLoader().getResourceAsStream("/tb.xml");
digester.parse(is);
} catch (IOException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} finally {
try {
if (is != null) {
is.close();
}
} catch (IOException exception) {
//
}
}
}
public String getDatabaseDriver() {
return databaseDriver;
}
public void setDatabaseDriver(String databaseDriver) {
this.databaseDriver = databaseDriver;
}
public String getDatabasePassword() {
return databasePassword;
}
public void setDatabasePassword(String databasePassword) {
this.databasePassword = databasePassword;
}
public String getDatabaseUrl() {
return databaseUrl;
}
public void setDatabaseUrl(String databaseUrl) {
this.databaseUrl = databaseUrl;
}
public String getDatabaseUser() {
return databaseUser;
}
public void setDatabaseUser(String databaseUser) {
this.databaseUser = databaseUser;
}
}
本文地址:http://com.8s8s.com/it/it14743.htm