Spring框架是怎么读取配置文件的?
内容摘自一下链接:http://songwensheng.iteye.com/blog/629578
1、XML文件格式
<beans>
<bean id="userDao" />
<bean id="userService" bean="userDao" />
</bean>
</beans>
2、读取代码
SAXBuilder sb = new SAXBuilder();
Document doc = sb.build(this.getClass().getClassLoader().getResource("beans.xml"));
Element root = doc.getRootElement();//获取根元素beans
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 obj =Class.forName(clazz).newInstance();
System.out.println(id);
System.out.println(clazz);
beans.put(id, obj);
for(Element propertyElement : (List<Element>)element.getChildren("property")) {
String name = propertyElement.getAttributeValue("name");//获取name=userDao中的userDao
String bean = propertyElement.getAttributeValue("bean");//获取dao的bean
Object beanObject = beans.get(bean);//userDaoImpl instance
String methodName = "set"+name.substring(0,1).toUpperCase()+name.substring(1);
System.out.println("method name:"+methodName);
Method m = obj.getClass().getMethod(methodName, beanObject.getClass().getInterfaces()[0]);//setUserDao(UserDao.class)
m.invoke(obj, beanObject);
1 楼 jianfeihit 2011-01-10 对于不同的解析XML技术的文章,我个人觉得SAX的这个还是比较清晰的。至少在处理属性和孩子结点的时候是这样的