搜索热词
将ApplicationContext.xml加载到java内存中
2,将对应的标签封装成java对象
在BeanConfig中存在一个Map 对应中的多个子元素,其中的name就是Map的键,本身作值;
3,实现加载方法:
package cn.lwuyang.exercise;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.dom4j.Document;
import org.dom4j.Element;
import cn.lwuyang.xml.utils.XmlUtils;
public class BeanLoadUtils {
public static Map load(String xmlName){
/**
* 0,创建Map集合容器
* 1,获取Document,在获取xml资源的根元素(root),再获取所有子元素,即bean元素
* 2,遍历所有的元素,再把元素映射成一个BeanConfig对象
*
*
* --->>这是一个BeanConfig对象
* 3,再将BeanConfig对象装载到Map集合中
*/
Map map = new LinkedHashMap();
//获取Document对象
Document doc = XmlUtils.getDocument(xmlName);
//得到root元素
Element root = doc.getRootElement();
//得到所有的
List eles = root.elements();
for (Element ele : eles) {
//将Element对象转换为BeanConfig对象
BeanConfig beanConfig = toBeanConfig(ele);
map.put(beanConfig.getId(),beanConfig);
}
return map;
}
/**
* 将转换为BeanConfig对象
* @param ele
* @return BeanConfig对象
*/
public static BeanConfig toBeanConfig(Element beanEle) {
/*
* 1创建BeanConfig对象
* 2获取beanEle的id属性值,调用beanConfig对象的setId()设置它
* 3获取beanEle的className属性值,调用beanConfig对象的setClassName()设置它
*/
BeanConfig beanConfig = new BeanConfig();
String id = beanEle.attributeValue("id");
String className= beanEle.attributeValue("className");
beanConfig.setId(id);
beanConfig.setClassName(className);
/**
* 映射子元素
* 1,获取beanEle的所有子元素
* 2,遍历子元素
* 3,把每一个子元素映射为PropertyConfig对象
* 4,调用BeanConfig对象的addPropertyConfig()方法完成添加操作
*/
List proElements = beanEle.elements();
for (Element propEle : proElements) {
//将转换为PropertyConfig对象
PropertyConfig propertyConfig = toPropertyConfig(propEle);
beanConfig.addPropertyConfig(propertyConfig);
}
return beanConfig;
}
/**
* 将转换为PropertyConfig
* @param propEle
* @return
*/
public static PropertyConfig toPropertyConfig(Element propEle) {
PropertyConfig propertyConfig = new PropertyConfig();
String name = propEle.attributeValue("name");
String value = propEle.attributeValue("value");
String ref = propEle.attributeValue("ref");
propertyConfig.setName(name);
propertyConfig.setValue(value);
propertyConfig.setRef(ref);
return propertyConfig;
}
}
总结
如果觉得编程之家网站内容还不错,欢迎将编程之家网站推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。