Spring原理模拟代码

时间:2014-12-16 17:36:48
【文件属性】:

文件名称:Spring原理模拟代码

文件大小:155KB

文件格式:ZIP

更新时间:2014-12-16 17:36:48

Spring,IOC控制反转

package com.ohc.spring; import java.lang.reflect.Method; import java.util.HashMap; import java.util.List; import java.util.Map; import org.jdom.Document; import org.jdom.Element; import org.jdom.input.SAXBuilder; public class ClassPathXmlApplicationContext implements BeanFactory { private Map beans = new HashMap(); @SuppressWarnings("unchecked") public ClassPathXmlApplicationContext() throws Exception { SAXBuilder sb = new SAXBuilder(); Document doc = sb.build(this.getClass().getClassLoader() .getResourceAsStream("beans.xml")); Element root = doc.getRootElement();// 获取根元素 List list = root.getChildren("bean");// 获取名字为bean的所有元素 for (int i = 0; i < list.size(); i++) { Element element = (Element) list.get(i); String id = element.getAttributeValue("id"); String clazz = element.getAttributeValue("class"); Object o = Class.forName(clazz).newInstance(); beans.put(id, o); for (Element propertyElement : (List) element .getChildren("property")) { String name = propertyElement.getAttributeValue("name"); String bean = propertyElement.getAttributeValue("bean"); Object beanObject = beans.get(bean); String methodName = "set" + name.substring(0, 1).toUpperCase() + name.substring(1); Method m = o.getClass().getMethod(methodName, beanObject.getClass().getInterfaces()[0]); m.invoke(o, beanObject); } } } @Override public Object getBean(String name) { return beans.get(name); } }


【文件预览】:
SpringPrinciple
----bin()
--------beans.xml(184B)
--------com()
----test()
--------com()
----.settings()
--------org.eclipse.jdt.core.prefs(629B)
----src()
--------beans.xml(184B)
--------com()
----.project(391B)
----.classpath(479B)
----lib()
--------jdom-1.1.2.jar(149KB)

网友评论