public interface ApplicationContext { public Object getBean(String beanId); } public class ClassPathXmlApplicationContext implements ApplicationContext{ private Map iocContet = new HashMap(); public ClassPathXmlApplicationContext(){ try{ String filePath = this.getClass().getResource("/applicationContext.xml").getPath(); filePath = new URLDecoder().decode(filePath, "UTF-8"); SAXReader reader = new SAXReader(); document document = reader.read(new File(filePath)); List org.dom4j dom4j2.1.1 jaxen jaxen1.1.1 bean = document.getRootElement().selectNodes("bean"); for (Node node : bean){ Element ele = (Element) node; String id = ele.attributevalue("id"); String className = ele.attributevalue("class"); Class c = Class.forName(className); Object obj = c.newInstance(); List properties = ele.selectNodes("property"); for (Node p : properties){ Element property = (Element) p; String propName = property.attributevalue("name"); String propValue = property.attributevalue("value"); String setMethodName = "set" + propName.substring(0, 1).toUpperCase() + propName.substring(1); System.out.println("准备执行" + setMethodName + "方法注入数据"); Method setMethod = c.getMethod(setMethodName, String.class); setMethod.invoke(obj, propValue); } iocContet.put(id, obj); } System.out.println(":ioc容器初始化完毕"); }catch (Exception e){ e.printStackTrace(); } } @Override public Object getBean(String beanId) { return iocContet.get(beanId); } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)