1.将xml文件转换成Document对象
2.通过xpath找到某个Element对象
3.通过属性名找到对应的属性值
4.通过该属性值反射出一个对象
依赖的类库:dom4j.jar及其依赖的xpath库jaxen.jar.
package com.life.util; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.io.SAXReader; public class BeanFactory { public static Object getBean(String id){ try { SAXReader reader = new SAXReader(); Document document = reader.read(BeanFactory.class.getClassLoader().getResourceAsStream("beans.xml")); //下面这两个获取document的方式也可以 //Document document = reader.read(BeanFactory.class.getResourceAsStream("/beans.xml")); //Document document = reader.read(BeanFactory.class.getResourceAsStream("../../../beans.xml")); Element element = (Element)document.selectSingleNode("//bean[@id='"+id+"']"); String value = element.attributeValue("class"); Class<?> clz = Class.forName(value); return clz.newInstance(); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(); } } }