package util; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.io.IOException; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.jdom.Document; import org.jdom.Element; import org.jdom.JDOMException; import org.jdom.input.SAXBuilder; public class MyApplicationContext { Document doc = null; Map beans = new HashMap(); public MyApplicationContext(String xmlName) { SAXBuilder sax = new SAXBuilder(); try { doc = sax.build(xmlName); initBeans(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } private void initBeans() throws Exception { Element root = doc.getRootElement(); // 得到beans List beanList = root.getChildren(); Iterator<Element> beanListIt = beanList.iterator(); while (beanListIt.hasNext()) { Element beanEle = beanListIt.next(); String id = beanEle.getAttributeValue("id"); String className = beanEle.getAttributeValue("class"); Object obj = Class.forName(className).newInstance(); beans.put(id, obj); // 得到propertys List proList = beanEle.getChildren(); Iterator<Element> proListIt = proList.iterator(); while (proListIt.hasNext()) { Element proEle = proListIt.next(); // 得到每个property中的参数,反射注入 String methodName = proEle.getAttributeValue("name"); String ref_id = proEle.getAttributeValue("ref"); Object ref_object = beans.get(ref_id); PropertyDescriptor[] pds = Introspector.getBeanInfo( obj.getClass()).getPropertyDescriptors(); for (PropertyDescriptor pd : pds) { if (pd.getName().equals(methodName)) { Method method = pd.getWriteMethod(); method.invoke(obj, ref_object); } } } } } public Object getBean(String id) { return beans.get(id); } } //模拟SpringFactory