日期:2014-05-16 浏览次数:20411 次
本文主要简述的内容有单例设计模式、dom4j解析xml文件(这里解析的数据库的配置文件)、通过解析出来的配置信息完成数据库的连接。
1、首先要看的是单例设计模式
单例设计模式的实现有两种:饿汉式(预先加载)、懒汉式(延迟加载),下面分别来看这两种实现方式。
(1)、饿汉式(预先加载)
public class Singleton{ private static Singleton instance = new Singleton(); private Singleton(){} public static synchronized Singleton getInstance(){ return instance; } }(2)懒汉式(延迟加载)
public class Singleton{ private static Singleton instance = null; private Singleton(){} public static synchronized Singleton getInstance(){ if(instance==null){ instance = new Singleton(); } return instance; } }
2、使用dom4j来完成数据库配置文件的解析
给出下面这个数据库的配置文件sys-config.xml
<?xml version="1.0" encoding="UTF-8"?> <config> <db-info> <driver>oracle.jdbc.driver.OracleDriver</driver> <url>jdbc:oracle:thin:@127.0.0.1:1521:ORCL</url> <user>username</user> <password>password</password> </db-info> </config>完成解析的java类:
(1)、保存数据库jdbc配置信息的模型类JdbcConfig.java
package org.ml.drp.util; /** * 用于保存数据库连接时的jdbc参数 * * @author MuLing * */ public class JdbcConfig { private String DbDriver; private String DbUrl; private String DbUser; private String DbPass; public String getDbDriver() { return DbDriver; } public void setDbDriver(String dbDriver) { DbDriver = dbDriver; } public String getDbUrl() { return DbUrl; } public void setDbUrl(String dbUrl) { DbUrl = dbUrl; } public String getDbUser() { return DbUser; } public void setDbUser(String dbUser) { DbUser = dbUser; } public String getDbPass() { return DbPass; } public void setDbPass(String dbPass) { DbPass = dbPass; } @Override public String toString() { return "JdbcConfig [DbDriver=" + DbDriver + ", DbUrl=" + DbUrl + ", DbUser=" + DbUser + ", DbPass=" + DbPass + "]"; } }(2)、解析数据库配置文件的工具类XmlConfigReader.java,这里使用单例模式完成,采用的是懒汉式。
package org.ml.drp.util; import java.io.InputStream; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; /** * 用于解析xml文件 * @author MuLing * */ public class XmlConfigReader { private JdbcConfig jdbcConfig = null; private static XmlConfigReader instance = null; private XmlConfigReader(){ SAXReader reader = new SAXReader();//取得SAXReader的对象 InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream("sys-config.xml");//得到输入流对象 jdbcConfig = new JdbcConfig(); Document doc = null; try { doc = reader.read(input); //进行读取 } catch (DocumentException e) { e.printStackTrace(); } //取得对应的节点对象 Element driverEle = (Element)doc.selectObject("/config/db-info/driver"); Element urlEle = (Element)doc.selectObject("/config/db-info/url"); Element userEle = (Element)doc.selectObject("/config/db-info/user"); Element passwordEle = (Element)doc.selectObject("/config/db-info/password"); jdbcConfig.setDbDriver(driverEle.getStringValue()); jdbcConfig.setDbUrl(urlEle.getStringValue()); jdbcConfig.setDbUser(userEle.getStringValue()); jdbcConfig.setDbPass(passwordEle.getStringValue()); } public static synchronized XmlConfigReader getInstance(){