ClassPathXmlApplicationContext, classpath
How Spring reads the configuration file beans. xml:
Public class ClassPathXmlApplicationContext implements BeanFactory {private Map <String, Object> beans = new HashMap <String, Object> (); // ClassPathXmlApplicationContext (String xml) 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"); for (int I = 0; I <list. size (); I ++) {Element element = (Element) list. get (I); String id = element. getAttributeValue ("id"); String clazz = element. getAttributeValue ("class"); // use reflection to generate Object o = Class. forName (clazz ). newInstance (); System. out. println (id); System. out. println (clazz); beans. put (id, o) ;}@ Override public Object getBean (String id) {return beans. get (id );}
<Bean id = "" class = "">
An id corresponds to a class, which is placed in the hashMap set and used as the primary key for query.
for(Element propertyElement : (List<Element>)element.getChildren("property")){ String name = propertyElement.getAttributeValue("name"); String beanInstance = propertyElement.getAttributeValue("bean"); //beanInstance ---> id--->haved bean new Object beanObject = beans.get(beanInstance); String methodName = "set" + name.substring(0,1).toUpperCase()+name.substring(1); System.out.println("method Name:"+methodName); Method m = o.getClass().getMethod(methodName, beanObject.getClass().getInterfaces()[0]); //two differrent object ,car human m.invoke(o, beanObject); }