XML文件
<?xml version="1.0" encoding="UTF-8"?> <config> <db-info> <driver-name>oracle.jdbc.driver.OracleDriver</driver-name> <url>jdbc:oracle:thin:@127.0.0.1:1521:orcl</url> <username>drp</username> <password>drp</password> </db-info> </config>
DBUtil测试类
package com.zjlolife.drp.util; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class DBUtil { public static Connection getConnection() { Connection ct = null; try { JdbcInfo info = ConfigReader.getInstance().getInfo(); Class.forName(info.getDriverName()); ct = DriverManager.getConnection(info.getUrl(), info.getUsername(), info.getPassword()); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return ct; } public static void main(String[] args) { DBUtil.getConnection(); System.out.println("ok"); } }
加载XML核心类ConfigReader.java
package com.zjlolife.drp.util; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; public class ConfigReader { private Document doc; private JdbcInfo info; public static ConfigReader instance = new ConfigReader(); private ConfigReader() { try { doc = new SAXReader().read(Thread.currentThread().getContextClassLoader().getResourceAsStream("sys-config.xml")); 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"); info = new JdbcInfo(); info.setDriverName(driverNameElt.getStringValue()); info.setUrl(urlElt.getStringValue()); info.setUsername(usernameElt.getStringValue()); info.setPassword(passwordElt.getStringValue()); } catch (DocumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static ConfigReader getInstance() { return instance; } public JdbcInfo getInfo() { return info; } public static void main(String[] args) { JdbcInfo info = ConfigReader.getInstance().getInfo(); System.out.println(info); } }
接收xml信息的类JdbcInfo.java
package com.zjlolife.drp.util;
public class JdbcInfo {
public String driverName;
public String url;
public String username;
public String password;
public String getDriverName() {
return driverName;
}
public void setDriverName(String driverName) {
this.driverName = driverName;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String toString() {
return this.getClass().getName() + "{driverName=" + this.driverName +
", url=" + this.url +
", username=" + this.username +
", password=" + this.password + "}";
}
}