2019年7月21日17:45:54 手写IOC容器,用到了dom解析

package com.yinjun.spring.xml;

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

import java.lang.reflect.Field;
import java.util.List;

/**
 * 手写一个IOC容器
 */
public class XmlTest {
    //自定义IOC解析器
    private String xmlPath;

    public XmlTest(String xmlPath) {
        this.xmlPath = xmlPath;
    }

    public Object getBean(String beanId) throws DocumentException, ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchFieldException {
        Object obj = null;
        SAXReader saxReader = new SAXReader();
        Document rootDocument = saxReader.read(this.getClass().getClassLoader().getResourceAsStream(xmlPath));
        Element rootElement = rootDocument.getRootElement();
        List elementList = rootElement.elements();
        for (Element selemenet : elementList) {
            String id = selemenet.attributeValue("id");
            if (!beanId.equals(id)) {
                continue;
            }
            String className = selemenet.attributeValue("class");
            Class objClass = Class.forName(className);
            obj = objClass.newInstance();
            List sonElements = selemenet.elements();
            for (Element sselement : sonElements) {
                String name = sselement.attributeValue("name");
                String value = sselement.attributeValue("value");
                Field nameField = objClass.getDeclaredField(name);
                nameField.setAccessible(true);
                nameField.set(obj, value);
            }
        }
        return obj;
    }

    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, InstantiationException, DocumentException, IllegalAccessException {
        XmlTest xmlTest = new XmlTest("test.xml");
        Long startTime = System.currentTimeMillis();
        User user1 = (User) xmlTest.getBean("user1");
        System.out.println(user1.getId() + "------" + user1.getName());
        System.out.println(System.currentTimeMillis() - startTime);
    }
}

你可能感兴趣的:(多线程)