zoukankan      html  css  js  c++  java
  • spring源码之bean解析

    源码分析入口:

    BeanFactory bf = new XmlBeanFactory(new ClassPathResource("bean.xml"));
    Person p = bf.getBean("person", Person.class);//创建bean的引用对象
    1. new ClassPathResource("bean.xml")
    |-- interface InputStreamSource  
                |-- InputStream getInputStream();
        |-- Resource extends InputStreamSource 
            |-- boolean exists(); // 存在性
            |-- boolean isReadable(); // 可读性
            |-- boolean isOpen(); // 是否处于打开状态
        |-- ClassPathResource implements Resource{
                @Override
                InputStream getInputStream() {
                    if (this.clazz != null){
                        is = this.clazz.getResourceAsStream(this.path);
                    } else {
                        is = this.classLoader.getResourceAsStream(this.path);
                    }
                }
            }
        |-- FileSystemResource implements Resource{
                @Override
                InputStream getInputStream() {
                    return new FileInputStream(this.file);
                }
            }
            ...
    2. new XmlBeanFactory(new ClassPathResource("bean.xml"))
    |-- XmlBeanFactory(Resource resource, BeanFactory parentBeanFactory)
            |-- super(parentBeanFactory) { // 忽略给定接口的自动装配
                    super();
                    ignoreDependencyInterface(BeanNameAware.class);
                    ignoreDependencyInterface(BeanFactoryAware.class);
                    ignoreDependencyInterface(BeanClassLoaderAware.class);
                }
            |-- this.reader.loadBeanDefinitions(resource) {
                    // 通过属性来记录已经加载的资源 this.resourceCurrentBeingLoaded -> new ThreadLocal<Set<EncodedResource>>;
                    Set<EncodedResource> currentResources = this.resourceCurrentBeingLoaded.get();
                    ...
                    // 真正处理业务
                    return doLoadBeanDefinitions(inputSource, encodedResource.getResource());
                }
                |-- doLoadBeanDefinitions(inputSource, encodedResource.getResource()) {
                        // 加载xml文件得到对应的Document
                        Document doc = doLoadDocument(inputSource, resource);
                        // 根据返回的Document对象注册Bean信息
                        registerBeanDefinitions(doc, resource) {
                            // 使用默认的DefaultBeanDefinitionDocumentReader实例化BeanDefinitionDocumentReader
                            BeanDefinitionDocumentReader documentReader = createBeanDefinitionDocumentReader();
                            // 记录统计前BeanDefiniton的加载个数
                            int countBefore = getRegistry().getBeanDefinitionCount();
                            // 加载及注册bean
                            documentReader.registerBeanDefinitions(doc, createReaderContext(resource)) {
                                this.readerContext = readerContext;
                                Element root = doc.getElement();
                                doRegisterBeanDefinitions(root) {
                                    // 处理profile
                                    if (root.getElement("profile").hasText()) ...
                                    // 专门处理解析
                                    BeanDefinitionParserDelegate parent = this.delegate;
                                    this.delegate = createHelper(readerContext, root, parent);
                                    // begin
                                    preProcessXml(root); // 钩子方法
                                    parseBeanDefinitions(root, this.delegate) {
                                        // 对beans的处理 
                                        if (delegate.isDefaultNamespace(root)) { // 默认标签
                                            NodeList nl = root.getChildNodes();
                                            for (int i = 0; i < nl.length(); i++) {
                                                Node node = nl.item(i);
                                                if (node instanceof Element) {
                                                    Element ele = (Element) node;
                                                    // 对bean的处理
                                                    parseDefaultElement(ele, delegate) {
                                                        // 对import标签处理
                                                        if (delegate.nodeNameEquals(ele, IMPORT_ELEMENT)){
                                                            importBeanDefinitionResource(ele);
                                                        }
                                                        // 对alias标签处理
                                                        else if (delegate.nodeNameEquals(ele, ALIAS_ELEMENT)){
                                                            processAliasRegistration(ele);
                                                        }
                                                        // 对bean标签处理
                                                        else if (delegate.nodeNameEquals(ele, BEAN_ELEMENT)){
                                                            processBeanDefinition(ele, delegate) {
                                                                // 委托BeanDefinitionParserDelegate类解析,bdHolder实例包含class、name、id、alias之类的属性
                                                                BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele) {
                                                                    // 解析id属性
                                                                    String id = ele.getAttribute(ID_ATTRIBUTE);
                                                                    // 解析name属性
                                                                    String nameAttr = ele.getAttribute(NAME_ATTRIBUTE);
                                                                    // 分割name属性
                                                                    List<String> aliases = new ArrayList<String>();
                                                                    if (StringUtils.hasLength(aliases)) {
                                                                        String[] nameArr = StringUtils.tokenizedToStringArray(nameAttr, ",");
                                                                        aliases.addAll(nameArr);
                                                                    }
                                                                    String beanName = id;
                                                                    if (!StringUtils.hasText(beanName) && !aliases.isEmpty()) {
                                                                        beanName = aliases.remove(0); //??
                                                                    }
                                                                    if (containingBean == null) {
                                                                        checkNameUniqueness(beanName, aliases, ele);
                                                                    }
                                                                    
                                                                    // 进一步解析其他所有属性并统一封装至GenericBeanDefinition
                                                                    AbstractBeanparseBeanDefinition beanDefinition = parseBeanDefinitionElement(ele, beanName, containingBean) {
                                                                        try {
                                                                            this.parseState.push(new BeanEntry(beanName));
                                                                            String className = null;
                                                                            // 解析class属性
                                                                            if (ele.hasAttribute(CLASS_ATTRIBUTE)) {
                                                                                className = ele.getAttribute(CLASS_ATTRIBUTE).trim();
                                                                            }
                                                                            // 解析parent属性
                                                                            String parent = null;
                                                                            if (ele.hasAttribute(PARENT_ATTRIBUTE)) {
                                                                                parent = ele.getAttribute(PARENT_ATTRIBUTE).trim();
                                                                            }
                                                                            // 创建用于属性承载的BeanDefinition
                                                                            AbstractBeanDefinition bd = createBeanDefinition(className, parent) {
                                                                                BeanDefinitionReaderUtils.createBeanDefinition(parentName, className, this.readerContext.getBeanClassLoader()) {
                                                                                    GenericBeanDefinition bd = new GenericBeanDefinition();
                                                                                    // parentName可能为空
                                                                                    bd.setParentName(parentName);
                                                                                    if (className != null) {
                                                                                        if (classLoader != null) {
                                                                                            bd.setBeanClass(ClassUtil.forName(className, classLoader));
                                                                                        } else {
                                                                                            bd.setBeanClassName(className);
                                                                                        }
                                                                                    }
                                                                                    return bd;
                                                                                }
                                                                            }
                                                                            
                                                                            // 硬编码解析默认的bean属性
                                                                            parseBeanDefinitionAttributes(ele, beanName, containingBean, bd) {
                                                                                // 解析scope属性
                                                                                // 解析singleton属性
                                                                                bd.setScope(ele.getAttribute(SCOPE_ATTRIBUTE) || ele.getAttribute(SINGLETON_ATTRIBUTE) || containingBean.getScope());
                                                                                // 解析abstract属性
                                                                                bd.setAbstract(ele.getAttribute(ABSTRACT_ATTRIBUTE));
                                                                                // 解析lazy-init属性
                                                                                bd.setLazyInit(lazy-init);
                                                                                // 解析autowire属性
                                                                                // 解析dependency-check属性
                                                                                // 解析dependency-on属性
                                                                                // 解析autowire-candidate属性
                                                                                // 解析primary属性
                                                                                // 解析init-method属性
                                                                                // 解析detory-method属性
                                                                                // 解析factory-method属性
                                                                                // 解析factory-bean属性
                                                                                ...
                                                                            }
                                                                            // 提取description
                                                                            bd.setDescription(DomUtils.getChildElementValueByTagName(ele, DESCRIPTION_ELEMENT));
                                                                            
                                                                            // 解析元数据
                                                                            parseMetaElements(ele, bd);
                                                                            // 解析lookup-method
                                                                            parseLookupOverriedSubElements(ele, bd.getMethodOverries());
                                                                            // 解析replacted-method属性
                                                                            parseReplactedMethodSubElements(ele, bd.getMethodOverries());
                                                                            
                                                                            // 解析构造函数参数
                                                                            parseConstructorArgElements(ele, bd);
                                                                            // 解析property子元素
                                                                            parsePropertyElements(ele, bd);
                                                                            // 解析qualifier子元素
                                                                            parseQualifierElements(ele, bd);
                                                                            
                                                                            bd.setResource(this.readerContext.getResource());
                                                                            bd.setSource(extractSource(ele));
                                                                            return bd;
                                                                        } catch (e) {
                                                                            throw e;
                                                                        } finally {
                                                                            this.parseState.pop();
                                                                        }
                                                                        return null;
                                                                    }
                                                                    if (beanDefinition != null) {
                                                                        if (!StringUtils.hasText(beanName)) {
                                                                            // 未指定beanName,使用默认规则为此bean生成beanName
                                                                            if (containingBean != null) {
                                                                                // 不存在name
                                                                                beanName = BeanDefinitionReaderUtils.generateBeanName(beanDefinition, this.readerContext.getRegistry(), true);
                                                                            } else {
                                                                                beanName = this.readerContext.generateBeanName(beanDefinition);
                                                                                String beanClassName = beanDefinition.getBeanClassName();
                                                                                if (beanClassName != null && beanName.startsWith(beanClassName) && beanName.length() > beanClassName.length() 
                                                                                    && !this.readerContext.getRegistry().IsBeanNameInUse(beanClassName)) {
                                                                                        aliases.add(beanClassName);
                                                                                }
                                                                            }
                                                                        }
                                                                        // 将获取到的信息封装到BeanDefinitionHolder中    
                                                                        String[] aliasesArray = StringUtils.toStringArray(aliases);
                                                                        return new BeanDefinitionHolder(beanDefinition, beanName, aliasesArray);
                                                                    }
                                                                    return null;
                                                                }
                                                                if (bdHolder != null) {
                                                                    // bdHolder不为空情况下,若存在默认标签的子节点下再有自定义属性,还需要再次注册
                                                                    bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);
                                                                    try {
                                                                        // 注册操作委托BeanDefinitionReaderUtils.registerBeanDefinition方法
                                                                        BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry());
                                                                    } catch (e) {
                                                                        throw e;
                                                                    }
                                                                    // 发出响应事件,通知想关的监听器,这个bean已经加载完成了
                                                                    getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder));
                                                                }
                                                            }
                                                        }
                                                        // 对beans标签处理
                                                        else if (delegate.nodeNameEquals(ele, NESTED_BEANS_ELEMENT)){
                                                            doRegisterBeanDefinitions(ele);
                                                        }
                                                    }
                                                } else {
                                                    // 对bean的处理
                                                    delegate.parseCustomElement(ele);
                                                }
                                            }
                                        } else { // 用户自定义标签
                                            // 对bean的处理
                                            delegate.parseCustomElement(ele);
                                        }
                                    }
                                    postProcessXml(root); // 钩子方法
                                    // end
                                    this.delegate = parent;
                                }
                            }
                            // 记录本次加载的BeanDefinition个数
                            return getRegistry().getBeanDefinitionCount() - countBefore;
                        }
                    }
  • 相关阅读:
    Android进阶之关闭所有activty
    弹出窗口插件欣赏
    关于之前放在google 的资源不能下载的解决方案
    图片垂直居中的使用技巧
    关于采用业务用例视图来展示、归纳、整理业务用例的三点指导原则
    操作系统引导的那点事
    可视化拾色器
    AE中删除属性字段
    AE中添加属性字段
    vs2005c#中用户组件在工具箱中不能自动出现的解决办法
  • 原文地址:https://www.cnblogs.com/ice-line/p/9965690.html
Copyright © 2011-2022 走看看