采用单例模式读取xml配置文件xml
1、添加两个包:dom4j-1.6.1.jar、jaxen-1.1-beta-6.jar
2、xml配置
<?xml version="1.0" encoding="UTF-8"?> <config> <db-info> <driver-name>com.mysql.jdbc.Driver</driver-name> <url>jdbc:mysql://localhost/test</url> <username>root</username> <password>root</password> </db-info> <item-dao>com.bjpowernode.drp.basedata.dao.ItemDao4MySqlImpl</item-dao> </config>
3、代码读取
package com.mysql.coon; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; /** * 采用单例模式读取xml配置文件sys-config.xml * @author Administrator * */ public class ConfigReader { private static ConfigReader instance = new ConfigReader(); private Document doc; private JdbcInfo jdbcInfo; private String itemDaoString; 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"); jdbcInfo = new JdbcInfo(); jdbcInfo.setDriverName(driverNameElt.getStringValue()); jdbcInfo.setUrl(urlElt.getStringValue()); jdbcInfo.setUsername(usernameElt.getStringValue()); jdbcInfo.setPassword(passwordElt.getStringValue()); //------------------------------------------------------------- Element itemDaoStringElt = (Element)doc.selectObject("/config/item-dao"); itemDaoString = itemDaoStringElt.getStringValue(); } catch (DocumentException e) { e.printStackTrace(); } } public static ConfigReader getInstance() { return instance; } public JdbcInfo getJdbcInfo() { return jdbcInfo; } public String getItemDaoString() { return itemDaoString; } public static void main(String[] args) { System.out.println(ConfigReader.getInstance().getJdbcInfo().getDriverName()); System.out.println(ConfigReader.getInstance().getJdbcInfo()); System.out.println(ConfigReader.getInstance().getItemDaoString()); } }
至于为什么要用单例?首先不懂单例是什么的查看我的微博:
http://my.oschina.net/marcello/blog/403983
然后这里讲为什么要用单例;1、因为这个是数据库配置信息,反正用户多次请求,如果用户未释放,这边不会再读取
2、读取的信息会再数据库连接中用到,所以要用单例
如果还是不明白可以咨询qq:648385408
email:laijingkang@163.com