采用单例模式读取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

转载于:https://www.cnblogs.com/marcello/p/4501509.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值