原文地址: http://blog.csdn.net/mlc1218559742/article/details/52776160
有没有发现上面的代码与利用反射实现工厂模式的代码很相似。对,你没有看错,Spring中的BeanFactory用到的就是简单工厂模式。
现在的思路就更加清晰了,要想实现Spring中的BeanFactory,无非就用到了以下几个技术:
1.使用简单工厂模式来处理bean容器。
2.解析xml文件,获取配置中的元素信息。
3.利用反射获实例化配置信息中的对象。
4.如果有对象注入,使用invoke()方法。
5.实例化的对象放入bean容器中,并提供getBean方法。
通过以上步骤就实现了spring的BeanFactory功能,只要在配置文件中配置好,实例化对象的事情交给BeanFactory来实现,用户不需要通过new对象的方式实例化对象,直接调用getBean方法即获取对象实例。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class BeanFactory { //bean容器 private Map<String, Object> contianer = new HashMap<String, Object>(); /** * <p>Discription:bean工厂的初始化</p> * @param xml xml配置文件路径 * @author : lcma * @update : 2016年9月20日上午9:04:41 */ public void init(String xml) { try { // 读取指定的配置文件 SAXReader reader = new SAXReader(); ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); // 从class目录下获取指定的xml文件 InputStream ins = classLoader.getResourceAsStream(xml); Document doc = reader.read(ins); Element root = doc.getRootElement(); Element foo; // 遍历bean for (Iterator i = root.elementIterator("bean"); i.hasNext();) { foo = (Element) i.next(); // 获取bean的属性id和class Attribute id = foo.attribute("id"); Attribute cls = foo.attribute("class"); // 利用Java反射机制,通过class的名称获取Class对象 Class<?> bean = Class.forName(cls.getText()); // 获取对应class的信息 java.beans.BeanInfo info = java.beans.Introspector.getBeanInfo(bean); // 获取其属性描述 java.beans.PropertyDescriptor pd[] = info.getPropertyDescriptors(); // 设置值的方法 Method mSet = null; // 创建一个对象 Object obj = bean.newInstance(); // 遍历该bean的property属性 for (Iterator ite = foo.elementIterator("property"); ite.hasNext();) { Element foo2 = (Element) ite.next(); // 获取该property的name属性 Attribute name = foo2.attribute("name"); String value = null; // 获取该property的子元素value的值 for (Iterator ite1 = foo2.elementIterator("value"); ite1.hasNext();) { Element node = (Element) ite1.next(); value = node.getText(); break; } for (int k = 0; k < pd.length; k++) { if (pd[k].getName().equalsIgnoreCase(name.getText())) { mSet = pd[k].getWriteMethod(); // 利用Java的反射机制调用对象的某个set方法,并将值设进去 mSet.invoke(obj, value); } } } // 将对象放入beanMap中,其中key为id值,value为对象 contianer.put(id.getText(), obj); } } catch (Exception e) { System.out.println(e.toString()); } } /** * <p>Discription:通过bean的id在容器中获取bean对象</p> * @param beanName bean的唯一标识id * @return * @author : lcma * @update : 2016年9月20日上午9:05:00 */ public Object getBean(String beanName) { Object obj = contianer.get(beanName); return obj; } }