zoukankan      html  css  js  c++  java
  • 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");
        }
    }
  • 相关阅读:
    第十五篇:在SOUI中消息通讯
    为GDI函数增加透明度处理
    第十四篇:在SOUI中使用定时器
    第十三篇:在SOUI中使用有窗口句柄的子窗口
    第十二篇:SOUI的utilities模块为什么要用DLL编译?
    第十一篇:SOUI系统资源管理
    第十篇:扩展SOUI的控件及绘图对象(ISkinObj)
    第九篇:在SOUI中使用多语言翻译
    第八篇:SOUI中控件事件的响应
    Linked List Cycle
  • 原文地址:https://www.cnblogs.com/pickKnow/p/11151768.html
Copyright © 2011-2022 走看看