微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Spring ioc xml 实例化bean 自己实现

public class DefClasspathXmlApplicationContext {

    private String xmlPath;

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

    public Object getBean(String beanId) throws Exception {
        if (StringUtils.isEmpty(xmlPath)) {
            throw new Exception("xmlPath is null");
        }
        // 获取xml 元素
        List<Element> elements = readElementsFromXml(xmlPath);
        // 获取xml id 对应的class
        String clazzStr = findClassByBeanId(elements, beanId);

        if (StringUtils.isEmpty(clazzStr)) {
            throw new Exception("clazzStr 不存在");
        }
        Class<?> clazz = Class.forName(clazzStr);
        Constructor<?> constructor = clazz.getDeclaredConstructor();
        constructor.setAccessible(true);
        Object newInstance = constructor.newInstance();
        return newInstance;
    }

    private String findClassByBeanId(List<Element> elements, String beanId) {
        for (Element element : elements) {

            if (element.attributeValue("id") != null && element.attributeValue("id").equals(beanId)) {
                return element.attributeValue("class");
            }
        }
        return "";
    }

    private List<Element> readElementsFromXml(String xmlPath2) throws DocumentException {
        SAXReader saxReader = new SAXReader();
        // this.getClass().getClassLoader().getResourceAsstream(xmlPath)
        // 就是从src/main/resource 下读取
        InputStream resourceAsstream = this.getClass().getClassLoader().getResourceAsstream(xmlPath);
        Document read = saxReader.read(resourceAsstream);
        Element rootElement = read.getRootElement();

        List<Element> elements = rootElement.elements();
        if (elements.isEmpty()) {
            return null;
        }
        return elements;
    }

    public static void main(String[] args) throws Exception {
        DefClasspathXmlApplicationContext defClasspathXmlApplicationContext = new DefClasspathXmlApplicationContext(
                "spring.xml");
        Object bean = defClasspathXmlApplicationContext.getBean("userServiceImpl");
    }
}

 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。