3.Spring-用反射模拟IoC
1.BeanFactory.java
1 package com.jike.spring.chapter03.reflect; 2 3 import java.io.InputStream; 4 import java.lang.reflect.Method; 5 import java.util.HashMap; 6 import java.util.Iterator; 7 import java.util.Map; 8 9 import org.dom4j.Attribute; 10 import org.dom4j.Document; 11 import org.dom4j.Element; 12 import org.dom4j.io.SAXReader; 13 14 public class BeanFactory { 15 16 private Map<String, Object> beanMap = new HashMap<String, Object>(); 17 18 /** 19 * bean工厂的初始化. 20 * 21 * @param xml xml配置文件 22 */ 23 public void init(String xml) { 24 try { 25 //1.创建读取配置文件的reader对象 26 SAXReader reader = new SAXReader(); 27 28 //2.获取当前线程中的类装载器对象 29 ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); 30 31 //3.从class目录下获取指定的xml文件 32 InputStream ins = classLoader.getResourceAsStream(xml); 33 Document doc = reader.read(ins); 34 Element root = doc.getRootElement(); 35 Element foo; 36 37 //4.遍历xml文件当中的Bean实例 38 for (Iterator i = root.elementIterator("bean"); i.hasNext();) { 39 foo = (Element) i.next(); 40 41 //5.针对每个一个Bean实例,获取bean的属性id和class 42 Attribute id = foo.attribute("id"); 43 Attribute cls = foo.attribute("class"); 44 45 //6.利用Java反射机制,通过class的名称获取Class对象 46 Class bean = Class.forName(cls.getText()); 47 //7.获取对应class的信息 48 java.beans.BeanInfo info = java.beans.Introspector.getBeanInfo(bean); 49 //8.获取其属性描述 50 java.beans.PropertyDescriptor pd[] = info.getPropertyDescriptors(); 51 52 //9.创建一个对象,并在接下来的代码中为对象的属性赋值 53 Object obj = bean.newInstance(); 54 55 //10.遍历该bean的property属性 56 for (Iterator ite = foo.elementIterator("property"); ite.hasNext();) { 57 Element foo2 = (Element) ite.next(); 58 59 //11.获取该property的name属性 60 Attribute name = foo2.attribute("name"); 61 String value = null; 62 63 //12.获取该property的子元素value的值 64 for (Iterator ite1 = foo2.elementIterator("value"); ite1.hasNext();) 65 { 66 Element node = (Element) ite1.next(); 67 value = node.getText(); 68 break; 69 } 70 71 //13.利用Java的反射机制调用对象的某个set方法,并将值设置进去 72 for (int k = 0; k < pd.length; k++) { 73 if (pd[k].getName().equalsIgnoreCase(name.getText())) 74 { 75 Method mSet = null; 76 mSet = pd[k].getWriteMethod(); 77 mSet.invoke(obj, value); 78 } 79 } 80 } 81 82 //14.将对象放入beanMap中,其中key为id值,value为对象 83 beanMap.put(id.getText(), obj); 84 } 85 } catch (Exception e) { 86 System.out.println(e.toString()); 87 } 88 } 89 90 /** 91 * 通过bean的id获取bean的对象. 92 * 93 * @param beanName 94 * bean的id 95 * @return 返回对应对象 96 */ 97 public Object getBean(String beanName) { 98 Object obj = beanMap.get(beanName); 99 return obj; 100 } 101 102 /** 103 * 测试方法. 104 * 105 * @param args 106 */ 107 public static void main(String[] args) { 108 BeanFactory factory = new BeanFactory(); 109 factory.init("conf/config.xml"); 110 JavaBean javaBean = (JavaBean) factory.getBean("javaBean"); 111 System.out.println("userName=" + javaBean.getUserName()); 112 System.out.println("password=" + javaBean.getPassword()); 113 } 114 }
You can do anything you set your mind to, man!