package com.lagou.edu.factory;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author 应癫
*
* 工厂类,生产对象(使用反射技术)
*/
public class BeanFactory {
/**
* 任务一:读取解析xml,通过反射技术实例化对象并且存储待用(map集合)
* 任务二:对外提供获取实例对象的接口(根据id获取)
*/
private static Map<String,Object> map = new HashMap<>(); // 存储对象
static {
// 任务一:读取解析xml,通过反射技术实例化对象并且存储待用(map集合)
// 加载xml
InputStream resourceAsStream = BeanFactory.class.getClassLoader().getResourceAsStream("beans.xml");
// 解析xml
SAXReader saxReader = new SAXReader();
try {
//<根据解析beans.xml完成beans.xml中每个bean所代表的对象的实例化>
Document document = saxReader.read(resourceAsStream);
Element rootElement = document.getRootElement();
List<Element> beanList = rootElement.selectNodes("//bean");
for (int i = 0; i < beanList.size(); i++) {
Element element = beanList.get(i);
// 处理每个bean元素,获取到该元素的id 和 class 属性
String id = element.attributeValue("id"); // accountDao
String clazz = element.attributeValue("class"); // com.lagou.edu.dao.impl.JdbcAccountDaoImpl
// 通过反射技术实例化对象
Class<?> aClass = Class.forName(clazz);
Object o = aClass.newInstance(); // 实例化之后的对象
// 存储到map中待用
map.put(id,o);
}
//<根据解析beans.xml完成beans.xml中对象与对象之间0需要依赖传值的部分>
// 实例化完成之后维护对象的依赖关系,检查哪些对象需要传值进入,根据它的配置,我们传入相应的值
// 有property子元素的bean就有传值需求
List<Element> propertyList = rootElement.selectNodes("//property");
// 解析property,获取父元素
for (int i = 0; i < propertyList.size(); i++) {
Element element = propertyList.get(i); //<property name="AccountDao" ref="accountDao"></property>
String name = element.attributeValue("name");
String ref = element.attributeValue("ref");
// 找到当前需要被处理依赖关系的bean,其实就是这个依赖关系所在节点的父节点
Element parent = element.getParent();
// 调用父节点元素对象(也就是bean节点)的反射功能
String parentId = parent.attributeValue("id");
Object parentObject = map.get(parentId);
// 遍历父对象中的所有方法,找到"set" + name
Method[] methods = parentObject.getClass().getMethods();
for (int j = 0; j < methods.length; j++) {
Method method = methods[j];
//equalsIgnoreCase 忽略大小写比较
if(method.getName().equalsIgnoreCase("set" + name)) { // 该方法就是 setAccountDao(AccountDao accountDao)
//反射机制中,方法的执行,参数1代表要执行方法所属的对象,参数2代表要传入的值(参数)
method.invoke(parentObject,map.get(ref));
}
}
// 把处理之后的parentObject重新放到map中
map.put(parentId,parentObject);
}
} catch (DocumentException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
// 任务二:对外提供获取实例对象的接口(根据id获取)
public static Object getBean(String id) {
return map.get(id);
}
}
BeanFactory类代码示例
最新推荐文章于 2024-06-29 11:18:30 发布