将ApplicationContext.xml加载到java内存中

来源:互联网 发布:简单的视频剪辑软件 编辑:程序博客网 时间:2024/05/16 19:40

将ApplicationContext.xml加载到java内存中

<?xml version="1.0" encoding="UTF-8"?><beans><bean id="userDao" className="cn.itcast.dao.impl.UserDaoImpl"><property name="xmlName" value="users.xml"/></bean><bean id="bookDao" className="cn.itcast.dao.impl.BookDaoImpl"><property name="xmlName" value="books.xml"/></bean><bean id="userService" className="cn.itcast.dao.impl.UserServiceImpl"><property name="userDao" ref="userDao"/><property name="bookDao" ref="bookDao"/></bean></beans>

2,将对应的标签封装成java对象


在BeanConfig中存在一个Map<Stirng,PropertyConfig> 对应<bean>中的多个<property>子元素,其中<property>的name就是Map的键,<property>本身作值;


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<String,BeanConfig> load(String xmlName){/** * 0,创建Map集合容器 * 1,获取Document,在获取xml资源的根元素(root),再获取所有子元素,即bean元素 * 2,遍历所有的<bean>元素,再把<bean>元素映射成一个BeanConfig对象 * <bean id="userDao" className="cn.itcast.dao.impl.UserDaoImpl"> *    <property name="xmlName" value="users.xml"/>     * </bean>--->>这是一个BeanConfig对象     * 3,再将BeanConfig对象装载到Map集合中 */Map<String,BeanConfig> map = new LinkedHashMap<String,BeanConfig>();//获取Document对象Document doc = XmlUtils.getDocument(xmlName);//得到root元素Element root = doc.getRootElement();//得到所有的<bean>List<Element> eles =  root.elements();for (Element ele : eles) {//将Element对象转换为BeanConfig对象BeanConfig beanConfig = toBeanConfig(ele);map.put(beanConfig.getId(),beanConfig);}return map;}/** * 将<bean>转换为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);/** * 映射<property>子元素 * 1,获取beanEle的所有<property>子元素 * 2,遍历<property>子元素 * 3,把每一个<property>子元素映射为PropertyConfig对象 * 4,调用BeanConfig对象的addPropertyConfig()方法完成添加操作 */List<Element> proElements = beanEle.elements();for (Element propEle : proElements) {//将<property>转换为PropertyConfig对象PropertyConfig propertyConfig = toPropertyConfig(propEle);beanConfig.addPropertyConfig(propertyConfig);}return beanConfig;}/** * 将<propeerty>转换为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;}}



0 0
原创粉丝点击