自己实现的,程序写的土了点,很多情况没去考虑,主要是复习理解怎么使用反射来实现spring 的依赖注入。
package dom4jtest; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.List; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; public class Test3 { private static Object o1; public static void main(String[] args) { BeanA ba = (BeanA) getBean("beanA"); ba.getBeanB().show(); } public static Object getBean(String name){ if(o1==null) o1 = setBean(name); return o1; } @SuppressWarnings("unchecked") public static Object setBean(String name){ SAXReader sr = new SAXReader(); Object o = null; Class clz = null; Class clz2 = null; String ref = null; String name1 = null; try { Document doc = sr.read(Test3.class.getClassLoader().getResourceAsStream("beans.xml")); Element e = doc.getRootElement(); @SuppressWarnings("unchecked") List<Element> eles = e.elements(); for(Element ee : eles){ if(ee.attributeValue("id")!=null){ if(ee.attributeValue("id").equals(name)){ clz = Class.forName(ee.attributeValue("class")); o = clz.newInstance(); List<Element> elus = ee.elements("property"); ref = elus.get(0).attributeValue("ref"); name1 = elus.get(0).attributeValue("name"); if(ref!=null&&name1!=null){ for(Element eee:eles){ if(eee.attributeValue("id")!=null){ if(eee.attributeValue("id").equals(ref)){ clz2 = Class.forName(eee.attributeValue("class")); name1 ="set"+ name1.substring(0, 1).toUpperCase() + name1.substring(1); Method m = clz.getDeclaredMethod(name1,clz2); m.invoke(o, clz2.newInstance()); } } } } } } } } catch (DocumentException e) { e.printStackTrace(); } catch (ClassNotFoundException e1) { e1.printStackTrace(); } catch (InstantiationException e1) { e1.printStackTrace(); } catch (IllegalAccessException e1) { e1.printStackTrace(); } catch (IllegalArgumentException e1) { e1.printStackTrace(); } catch (InvocationTargetException e1) { e1.printStackTrace(); } catch (NoSuchMethodException e1) { e1.printStackTrace(); } catch (SecurityException e1) { e1.printStackTrace(); } return o; } }