XML综合案例

xml的综合案例

  • 需求和分析
  • 准备数据
  • BeanConfig对象
  • 解析xml并封装到BeanConfig
  • 反射实例化对象

准备数据

  • 创建User类
package bull06.XMLTest;

public class User {
    private String uid;
    private String userName;
    private String userPasswd;
    public String getUid() {
        return uid;
    }
    public void setUid(String uid) {
        this.uid = uid;
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public String getUserPasswd() {
        return userPasswd;
    }
    public void setUserPasswd(String userPasswd) {
        this.userPasswd = userPasswd;
    }
    @Override
    public String toString() {
        return "User [uid=" + uid + ", userName=" + userName + ", userPasswd="
                + userPasswd + "]";
    }


}
  • 创建Book类
package bull06.XMLTest;

public class Book {
    private String bid;
    private String title;
    private Integer price;
    public String getBid() {
        return bid;
    }
    public void setBid(String bid) {
        this.bid = bid;
    }
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public Integer getPrice() {
        return price;
    }
    public void setPrice(Integer price) {
        this.price = price;
    }
    @Override
    public String toString() {
        return "Book [bid=" + bid + ", title=" + title + ", price=" + price
                + "]";
    }


}
  • 创建beans.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<beans>
    <bean id="uid001" className="bull06.XMLTest.User">
        <property name="uid" value="u001"></property>
        <property name="userName"   value="kobe"></property>
        <property name="userPasswd" value="123456"></property>
    </bean>

    <bean id="bid001" className="bull06.XMLTest.Book">
        <property name="bid" value="b001"></property>
        <property name="title" value="myBook"></property>
        <property name="price" value="999"></property>
    </bean>
</beans>

创建BeanConfig类

package bull06.XMLTest;

import java.util.Properties;
/*
 * BeanConfig用于封装存储从XML中获取的数据
 */
public class BeanConfig {
    private String id;
    private String className;
    private Properties prop = new Properties();


    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getClassName() {
        return className;
    }
    public void setClassName(String className) {
        this.className = className;
    }
    public Properties getProp() {
        return prop;
    }
    public void setProp(Properties prop) {
        this.prop = prop;
    }
    @Override
    public String toString() {
        return "BeanConfig [id=" + id + ", className=" + className + ", prop="
                + prop + "]";
    }


}

解析XML文件并封装到BeanConfig的一个对象中

package bull06.XMLTest;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class BeanFactory {
    //1.1提供Map存放bean.xml配置文件中的所有内容,且易于快速查询
    private static Map<String,BeanConfig> cache = new HashMap<String,BeanConfig>();
    //1.2解析XML,将数据添加到map中
    static{
        try {
            //1)加载XML文件,获得document
            SAXReader saxReader = new SAXReader();

            //2)获得根元素<beans>
            Document document = saxReader.read("beans.xml");
            Element Bean = document.getRootElement();

            //3)获得所有<bean>元素
            List<Element> allBean = Bean.elements("bean");
            //4)获得id和className
            for (Element beans : allBean) {
                String id = beans.attributeValue("id");
                String className = beans.attributeValue("className");

                /**创建BeanConfig对象并配置id和className*/
                BeanConfig beanConfig = new BeanConfig();
                beanConfig.setId(id);
                beanConfig.setClassName(className);

                //5)获得<property>元素
                List<Element> allProperty = beans.elements("property");
                //6)获得name和value属性
                for (Element property : allProperty) {
                    String name = property.attributeValue("name");
                    String value = property.attributeValue("value");

                    /**将name和value封装到beanConfig.prop中*/
                    beanConfig.getProp().setProperty(name, value);
                }

                /**将封装好的beanConfig封装到Map中*/
                cache.put(id, beanConfig);
            }
            System.out.println("数据初始化成功:"+cache);

        } catch (Exception e) {
            //将编译时异常转化为运行时异常
            throw new RuntimeException(e);
        }
    }

    public static Object getBean(String beanId) {
        //通过beanId从Map中获取beanConfig
        BeanConfig beanConfig = cache.get(beanId);
        if(beanConfig == null) {
            throw new RuntimeException("获取的对象[" + beanConfig + "]不存在");
        }

        try {
            //通过beanConfig.className获取实例对象
            String className = beanConfig.getClassName();
            Class clazz = Class.forName(className);
            Object obj = clazz.newInstance();

            //循环遍历beanConfig.prop,使用BeanUtils进行数据封装
            for (String name : beanConfig.getProp().stringPropertyNames()) {
                //根据name获取value
                String value = beanConfig.getProp().getProperty(name);
                //使用BeanUtils进行数据封装,类似于set方法
                BeanUtils.setProperty(obj, name, value);
            }

            return obj;

        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }
}

反射实例化对象

package bull06.XMLTest;

import org.junit.Test;

public class GetBean {
    @Test
    public void get() {
        User user = (User)BeanFactory.getBean("uid001");
        System.out.println(user);

        Book book = (Book)BeanFactory.getBean("bid001");
        System.out.println(book);
    }
}

结果:
    数据初始化成功:{bid001=BeanConfig [id=bid001, className=bull06.XMLTest.Book, prop={bid=b001, price=999, title=myBook}], uid001=BeanConfig [id=uid001, className=bull06.XMLTest.User, prop={userPasswd=123456, uid=u001, userName=kobe}]}
    User [uid=u001, userName=kobe, userPasswd=123456]
    Book [bid=b001, title=myBook, price=999]

(解析XML时要用到的Dom4j):

package bull05.XMLPrase;

import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.junit.Test;

/*
 * 解析XML
 */
public class Dom4jDemo {
    @Test
    public void Prase() throws DocumentException {
        //1.核心类
        SAXReader sexReader = new SAXReader();

        //2.获得Document(整个XML)
        Document document = sexReader.read("beans.xml");

        //3.获得beans
        Element rootElement = document.getRootElement();

        //4.获得bean
        List<Element> allBeanElement =  rootElement.elements("bean");
        for (Element element : allBeanElement) {
            String id = element.attributeValue("id");
            String className = element.attributeValue("className");
            System.out.println("bean属性:" + id + "," + className);

            //5.获得property
            List<Element> allProperty = element.elements("property");
            for (Element element2 : allProperty) {
                String name = element2.attributeValue("name");
                String value = element2.attributeValue("value");
                System.out.println("property属性:" + name+ "," + value);
            }
            System.out.println();
        }
    }
}

结果:
    bean属性:uid001,bull06.XMLTest.User
    property属性:uid,u001
    property属性:userName,kobe
    property属性:userPasswd,123456

    bean属性:bid001,bull06.XMLTest.Book
    property属性:bid,b001
    property属性:title,myBook
    property属性:price,999

猜你喜欢

转载自blog.csdn.net/sinat_40662281/article/details/79887155