package com.itheima.factor;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import java.io.InputStream;
//生产指定id 的对象实例
public class BeanFactory {
public static Object getBean(String id) {
try {
//1,类加载器读取beans.xml
InputStream in = BeanFactory.class.getClassLoader().getResourceAsStream("beans.xml");
//2,dom4j解析xml
Document document = new SAXReader().read(in);
//3,编写xpath表达式
String xpath = "//bean[@id='"+id+"']";
//4,解析指定的id标签
Element bean = (Element) document.selectSingleNode(xpath);
//5,获取class属性值
String className = bean.attribute("class").getValue();
//6,反射创建对象实例返回
return Class.forName(className).newInstance();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("对象创建失败");
}
}
}
单例对象
package com.itheima.factor;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
//生产指定id 的对象实例
public class BeanFactory {
private static Map ioc =new HashMap<>();
static{
try {
//1,类加载器读取beans.xml
InputStream in = BeanFactory.class.getClassLoader().getResourceAsStream("beans.xml");
//2,dom4j解析xml
Document document = new SAXReader().read(in);
//解析所有的bean标签
String xpath = "//bean";
List elementList = document.selectNodes(xpath);
//遍历
for (Element element : elementList) {
String id = element.attributeValue("id");
String className = element.attributeValue("class");
Object instanse = Class.forName(className).newInstance();
ioc.put(id,instanse);
}
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("对象创建失败");
}
}
public static Object getBean(String id) {
return ioc.get(id);
}
}



