这是一个简单实现读取properties、xml格式的配置文件的小案例。虽然实际项目中可能不是这样实现的。作为了解也是不错的。回头有空研究了【Apache Commons Configuration对properties、xml配置文件的读写】,再来分享!支持源码下载哦!
【PersonDao】
package com.athl.dao.impl;
import com.athl.dao.IPersonDao;
public class PersonDao implements IPersonDao {
public void display(){
System.out.println("我被new出来的PersonDao对象调用了");
}
}
【PersonService】
package com.athl.service;
import java.io.InputStream;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.ResourceBundle;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import com.athl.dao.IPersonDao;
import com.athl.dao.impl.PersonDao;
@SuppressWarnings({ "rawtypes", "unchecked" })
public class PersonService {
private IPersonDao dao;
/**
* 一、读取properties类型文件
*/
//方法一:java.util.ResourceBundle读取properties类型文件
{
ResourceBundle rb =ResourceBundle.getBundle("dao");
try {
dao=(PersonDao)Class.forName(rb.getString("PersonDao")).newInstance();
} catch (Exception e) {
e.printStackTrace();
}
}
//方法二:java.util.Properties读取properties类型文件
{
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("dao.properties");
Properties p = new Properties();
try {
p.load(inputStream);
dao=(PersonDao)Class.forName(p.getProperty("PersonDao")).newInstance();
} catch (Exception e) {
e.printStackTrace();
}
}
/* 小结:以上两种方式都是读取src根目录下的文件 */
/**
* 二、读取xml类型文件
*/
{
try {
//1.获取解析器
SAXReader reader = new SAXReader();
//2.解析xml获取代表整个文档的dom对象
Document dom=null;
dom = reader.read("dao.xml");
//3.获取根节点
Element root = dom.getRootElement();
List<Element> list = root.elements();
for(Iterator it= list.iterator();it.hasNext();){
Element element = (Element) it.next();
String ClassName=element.attributeValue("name");
if("PersonDao".equals(ClassName)){
dao=(PersonDao)Class.forName(element.attributeValue("value")).newInstance();
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
/* 小结:dom4j读取项目根目录下的xml文件 */
//调用
public void run() {
dao.display();
}
//运行测试
public static void main(String[] args) {
new PersonService().run();
}
}
【控制台打印】
我被new出来的PersonDao对象调用了
本文提供了一个简单的示例,展示了如何使用Java读取properties和xml格式的配置文件,并通过PersonDao和PersonService两个类实现了具体的读取逻辑。
854

被折叠的 条评论
为什么被折叠?



