步骤1、编写xml配置文件;2、编写实体类JdbcConfig;3、在编写XMLJdbcConfigReader来读取xml配置文件。
步骤1、编写xml配置文件
<?xml version="1.0" encoding="utf-8" ?> <!-- 数据库相关信息: 1、驱动;2、url;3、user;4、password --> <config> <db-info> <driver-name>com.mysql.jdbc.Driver</driver-name> <url>jdbc:mysql://localhost:3306/test?autoReconnect=true&useUnicode=true&characterEncoding=UTF-8</url> <user-name>root</user-name> <password>root</password> </db-info> </config>
步骤2、编写实体类JdbcConfig
package net.etwo.model; public class JdbcConfig { /** * 数据库相关信息 * 1、驱动;2、url;3、user;4、password */ private String driverName; private String url; private String user; private 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 getUser() { return user; } public void setUser(String user) { this.user = user; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Override public String toString() { // TODO Auto-generated method stub return "driverName:" + this.driverName + "\nurl:" + this.url + "\nuser:" + this.user + "\npassword:" + this.password; } }
步骤3、在编写XMLJdbcConfigReader来读取xml配置文件
package net.etwo.util; import java.io.InputStream; import net.etwo.model.JdbcConfig; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; public class XMLJdbcConfigReader { /** * 采用单例模式解析XML */ private static XMLJdbcConfigReader instance; private static JdbcConfig jdbcConfig = new JdbcConfig(); private XMLJdbcConfigReader() { //解析XML InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("sys-config.xml"); SAXReader reader = new SAXReader(); try { Document doc = reader.read(is); Element eleDriverName = (Element)doc.selectObject("/config/db-info/driver-name"); Element eleUrl = (Element)doc.selectObject("/config/db-info/url"); Element eleUser = (Element)doc.selectObject("/config/db-info/user-name"); Element elePassword = (Element)doc.selectObject("/config/db-info/password"); String driverName = eleDriverName.getStringValue(); String url = eleUrl.getStringValue(); String user = eleUser.getStringValue(); String password = elePassword.getStringValue(); jdbcConfig.setDriverName(driverName); jdbcConfig.setUrl(url); jdbcConfig.setUser(user); jdbcConfig.setPassword(password); } catch (DocumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static synchronized XMLJdbcConfigReader getInstance() { if(instance ==null) { instance = new XMLJdbcConfigReader(); } return instance; } public JdbcConfig getJdbcConfig() { return jdbcConfig; } public static void main(String[] args) { new XMLJdbcConfigReader().getInstance(); System.out.println(jdbcConfig); } }