模拟实现Spring框架
Spring框架主要就是使用反射机制实现IOC/DI。
applicationContext.xml
<beans><bean id="u" /><bean id="userService" ><property name="userDAO" bean="u"/></bean></beans>
BeanFactory.java
public interface BeanFactory {public Object getBean(String id);}ClassPathXmlApplicationContext.java
public class ClassPathXmlApplicationContext implements BeanFactory {private Map<String , Object> beans = new HashMap<String, Object>();public ClassPathXmlApplicationContext() throws Exception {SAXBuilder sb=new SAXBuilder(); Document doc=sb.build(this.getClass().getClassLoader().getResourceAsStream("beans.xml")); //构造文档对象 Element root=doc.getRootElement(); //获取根元素:beans List list=root.getChildren("bean");//获取名字为:bean 的所有元素 for(int i=0;i<list.size();i++){ //对元素bean进行遍历 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);//放入Spring容器中 List<Element> le = element.getChildren("property"); for(Element propertyElement : le) { 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); //获取set方法名 Method m = o.getClass().getMethod(methodName, beanObject.getClass().getInterfaces()[0]); m.invoke(o, beanObject);//执行此set方法 } } }public Object getBean(String id) {return beans.get(id);}}?简单Spring框架就完成了,下面就是如何使用了:
BeanFactory applicationContext = new ClassPathXmlApplicationContext();UserService service = (UserService)applicationContext.getBean("userService");?