用xml保存数据库配置文件sys-config.xml <?xml version="1.0" encoding="UTF-8"?> <config> <db-info> <driver-name>oracle.jdbc.driver.OracleDriver</driver-name> <url>jdbc:oracle:thin:@localhost:1521:orcl</url> <username>scott</username> <password>tiger</password> </db-info> </config> 新建XMLConfigReader.java 采用单例模式解析sys-config.xml文件 import java.io.InputStream; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.io.SAXReader; public class XMLConfigReader { private static XMLConfigReader instance = null; private JdbcConfig jdbcConfig = new JdbcConfig(); private XMLConfigReader(){ SAXReader reader = new SAXReader(); InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("sys-config.xml"); try { Document doc = reader.read(in); Element drivernameElt = (Element)doc.selectObject("/config/db-info/driver-name"); Element urlElt = (Element)doc.selectObject("/config/db-info/url"); Element usernameElt = (Element)doc.selectObject("/config/db-info/username"); Element passwordElt = (Element)doc.selectObject("/config/db-info/password"); jdbcConfig.setDrivername(drivernameElt.getStringValue()); jdbcConfig.setUrl(urlElt.getStringValue()); jdbcConfig.setUsername(usernameElt.getStringValue()); jdbcConfig.setPassword(passwordElt.getStringValue()); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } public static synchronized XMLConfigReader getXmlConfigReader(){ if (instance == null) { instance = new XMLConfigReader(); } return instance; } public JdbcConfig getJdbcConfig() { return jdbcConfig; } }