Spring IOC初始化源码跟踪小记

  • 1、开始
public ClassPathXmlApplicationContext(String configLocation) throws BeansException {
        this(new String[]{configLocation}, true, (ApplicationContext)null);
}

public ClassPathXmlApplicationContext(String[] configLocations, boolean refresh, ApplicationContext parent) throws BeansException {
    // 初始化上下文环境
    super(parent);
    // 保存配置信息到configLocations
    this.setConfigLocations(configLocations);
    if (refresh) {
        // 刷新
        this.refresh();
    }

}
  • 2、refresh()
public void refresh() throws BeansException, IllegalStateException {
    Object var1 = this.startupShutdownMonitor;
    synchronized(this.startupShutdownMonitor) {
        // 准备对上下文刷新
        this.prepareRefresh();
        // 获取新的BeanFactory
        ConfigurableListableBeanFactory beanFactory = this.obtainFreshBeanFactory();
        this.prepareBeanFactory(beanFactory);

        try {
            this.postProcessBeanFactory(beanFactory);
            this.invokeBeanFactoryPostProcessors(beanFactory);
            this.registerBeanPostProcessors(beanFactory);
            this.initMessageSource();
            this.initApplicationEventMulticaster();
            this.onRefresh();
            this.registerListeners();
            this.finishBeanFactoryInitialization(beanFactory);
            this.finishRefresh();
        } catch (BeansException var5) {
            this.destroyBeans();
            this.cancelRefresh(var5);
            throw var5;
        }

    }
}
  • 3、obtainFreshBeanFactory()
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
    // 刷新BeanFactory
    this.refreshBeanFactory();
    // 获取BeanFactory
    ConfigurableListableBeanFactory beanFactory = this.getBeanFactory();
    if (this.logger.isDebugEnabled()) {
        this.logger.debug("Bean factory for " + this.getDisplayName() + ": " + beanFactory);
    }

    return beanFactory;
}
  • 4、refreshBeanFactory();
protected final void refreshBeanFactory() throws BeansException {
    // 保证是一个全新的BeanFactory
    if (this.hasBeanFactory()) {
        this.destroyBeans();
        this.closeBeanFactory();
    }

    try {
        // 创建新的BeanFactory
        DefaultListableBeanFactory beanFactory = this.createBeanFactory();
        beanFactory.setSerializationId(this.getId());
        this.customizeBeanFactory(beanFactory);
        // 加载所有定义的Bean
        this.loadBeanDefinitions(beanFactory);
        Object var2 = this.beanFactoryMonitor;
        synchronized(this.beanFactoryMonitor) {
            this.beanFactory = beanFactory;
        }
    } catch (IOException var5) {
        throw new ApplicationContextException("I/O error parsing bean definition source for " + this.getDisplayName(), var5);
    }
}
  • 5、loadBeanDefinitions(beanFactory)
protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
    // 为给定的BeanFactory创建一个新的XmlBeanDefinitionReader
    XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);
    beanDefinitionReader.setEnvironment(this.getEnvironment());
    beanDefinitionReader.setResourceLoader(this);
    beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));
    // 初始化XmlBeanDefinitionReader
    this.initBeanDefinitionReader(beanDefinitionReader);
    // 加载BeanDefinition
    this.loadBeanDefinitions(beanDefinitionReader);
}

protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws IOException {
    String[] configLocations = this.getConfigLocations();
    if (configLocations != null) {
        String[] arr$ = configLocations;
        int len$ = configLocations.length;

        for(int i$ = 0; i$ < len$; ++i$) {
            String configLocation = arr$[i$];
            // XmlBeanDefinitionReader根据配置信息加载BeanDefinition
            reader.loadBeanDefinitions(configLocation);
        }
    }

}
  • 6、reader.loadBeanDefinitions(configLocation)
public int loadBeanDefinitions(String location) throws BeanDefinitionStoreException {
    return this.loadBeanDefinitions(location, (Set)null);
}

public int loadBeanDefinitions(String location, Set<Resource> actualResources) throws BeanDefinitionStoreException {
    ResourceLoader resourceLoader = this.getResourceLoader();
    if (resourceLoader == null) {
        throw new BeanDefinitionStoreException("Cannot import bean definitions from location [" + location + "]: no ResourceLoader available");
    } else {
        // ... ...
        } else {
            try {
                Resource[] resources = ((ResourcePatternResolver)resourceLoader).getResources(location);
                // 这里
                loadCount = this.loadBeanDefinitions(resources);
                // ... ...
            } catch (IOException var10) {
                throw new BeanDefinitionStoreException("Could not resolve bean definition resource pattern [" + location + "]", var10);
            }
        }
    }
}
  • 7、loadBeanDefinitions(resources);
public int loadBeanDefinitions(Resource resource) throws BeanDefinitionStoreException {
    return this.loadBeanDefinitions(new EncodedResource(resource));
}

public int loadBeanDefinitions(EncodedResource encodedResource) throws BeanDefinitionStoreException {
    // ... ...
    if (!((Set)currentResources).add(encodedResource)) {
        // ... ...
    } else {
        int var5;
        try {
            InputStream inputStream = encodedResource.getResource().getInputStream();
            try {
                // ... ...
                // 这里呀
                var5 = this.doLoadBeanDefinitions(inputSource, encodedResource.getResource());
            } finally {
                inputStream.close();
            }
        } catch (IOException var15) {
            // ... ...
        } finally {
            // ... ...
        }
        return var5;
    }
}

protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource) throws BeanDefinitionStoreException {
    try {
        int validationMode = this.getValidationModeForResource(resource);
        Document doc = this.documentLoader.loadDocument(inputSource, this.getEntityResolver(), this.errorHandler, validationMode, this.isNamespaceAware());
        // 注册
        return this.registerBeanDefinitions(doc, resource);
    } catch (Throwable var10) {
        // catchs ... ...
    }
}

public int registerBeanDefinitions(Document doc, Resource resource) throws BeanDefinitionStoreException {

    BeanDefinitionDocumentReader documentReader = this.createBeanDefinitionDocumentReader();
    documentReader.setEnvironment(this.getEnvironment());
    int countBefore = this.getRegistry().getBeanDefinitionCount();
    // 准备解析
    documentReader.registerBeanDefinitions(doc, this.createReaderContext(resource));
    return this.getRegistry().getBeanDefinitionCount() - countBefore;
}
  • 8、registerBeanDefinitions(doc, this.createReaderContext(resource))
public void registerBeanDefinitions(Document doc, XmlReaderContext readerContext) {
     // ... ...
     this.doRegisterBeanDefinitions(root);
 }

protected void doRegisterBeanDefinitions(Element root) {
    String profileSpec = root.getAttribute("profile");
    if (StringUtils.hasText(profileSpec)) {
        Assert.state(this.environment != null, "environment property must not be null");
        String[] specifiedProfiles = StringUtils.tokenizeToStringArray(profileSpec, ",; ");
        if (!this.environment.acceptsProfiles(specifiedProfiles)) {
            return;
        }
    }

    BeanDefinitionParserDelegate parent = this.delegate;
    this.delegate = this.createHelper(this.readerContext, root, parent);
    this.preProcessXml(root);
    // 解析
    this.parseBeanDefinitions(root, this.delegate);
    this.postProcessXml(root);
    this.delegate = parent;
}

protected void parseBeanDefinitions(Element root, BeanDefinitionParserDelegate delegate) {
    if (delegate.isDefaultNamespace(root)) {
        NodeList nl = root.getChildNodes();

        for(int i = 0; i < nl.getLength(); ++i) {
            Node node = nl.item(i);
            if (node instanceof Element) {
                Element ele = (Element)node;
                if (delegate.isDefaultNamespace(ele)) {
                    // 在这
                    this.parseDefaultElement(ele, delegate);
                } else {
                    delegate.parseCustomElement(ele);
                }
            }
        }
    } else {
        delegate.parseCustomElement(root);
    }
}

private void parseDefaultElement(Element ele, BeanDefinitionParserDelegate delegate) {
    if (delegate.nodeNameEquals(ele, "import")) {
        this.importBeanDefinitionResource(ele);
    } else if (delegate.nodeNameEquals(ele, "alias")) {
        this.processAliasRegistration(ele);
    } else if (delegate.nodeNameEquals(ele, "bean")) {
        // 这里
        this.processBeanDefinition(ele, delegate);
    } else if (delegate.nodeNameEquals(ele, "beans")) {
        this.doRegisterBeanDefinitions(ele);
    }

}

// 最终的解析和注册
protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) {
    // 解析:将XML的元素解析为BeanDefinition,保存到BeanDefinitionHolder
    BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);
    if (bdHolder != null) {
        bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);
        try {
            // 注册:通过BeanDefinitionHolder将BeanDefinition进行注册
            BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, this.getReaderContext().getRegistry());
        } catch (BeanDefinitionStoreException var5) {
            this.getReaderContext().error("Failed to register bean definition with name '" + bdHolder.getBeanName() + "'", ele, var5);
        }

        this.getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder));
    }

}
  • 9、解析过程 delegate.parseBeanDefinitionElement(ele)
public BeanDefinitionHolder parseBeanDefinitionElement(Element ele) {
    return this.parseBeanDefinitionElement(ele, (BeanDefinition)null);
}

public BeanDefinitionHolder parseBeanDefinitionElement(Element ele, BeanDefinition containingBean) {
    // 继续
    AbstractBeanDefinition beanDefinition = this.parseBeanDefinitionElement(ele, beanName, containingBean);
    // ... ...
}

// 解析元素
public AbstractBeanDefinition parseBeanDefinitionElement(Element ele, String beanName, BeanDefinition containingBean) {
    // ... ...
    try {
        String parent = null;
        if (ele.hasAttribute("parent")) {
            parent = ele.getAttribute("parent");
        }
        // 创建beanDefinition
        AbstractBeanDefinition bd = this.createBeanDefinition(className, parent);
        // 解析属性
        this.parseBeanDefinitionAttributes(ele, beanName, containingBean, bd);
        bd.setDescription(DomUtils.getChildElementValueByTagName(ele, "description"));
        this.parseMetaElements(ele, bd);
        this.parseLookupOverrideSubElements(ele, bd.getMethodOverrides());
        this.parseReplacedMethodSubElements(ele, bd.getMethodOverrides());
        // 解析Constructor
        this.parseConstructorArgElements(ele, bd);
        // 解析Property
        this.parsePropertyElements(ele, bd);
        this.parseQualifierElements(ele, bd);
        bd.setResource(this.readerContext.getResource());
        bd.setSource(this.extractSource(ele));
        AbstractBeanDefinition var7 = bd;
        return var7;
    } catch (ClassNotFoundException var13) {
        // ... ...
    }
    return null;
}

// 解析Property
public void parsePropertyElement(Element ele, BeanDefinition bd) {
    String propertyName = ele.getAttribute("name");
    if (!StringUtils.hasLength(propertyName)) {
        this.error("Tag 'property' must have a 'name' attribute", ele);
    } else {
        this.parseState.push(new PropertyEntry(propertyName));

        try {
            if (!bd.getPropertyValues().contains(propertyName)) {
                // 解析Property value
                Object val = this.parsePropertyValue(ele, bd, propertyName);
                PropertyValue pv = new PropertyValue(propertyName, val);
                this.parseMetaElements(ele, pv);
                pv.setSource(this.extractSource(ele));
                bd.getPropertyValues().addPropertyValue(pv);
                return;
            }

            this.error("Multiple 'property' definitions for property '" + propertyName + "'", ele);
        } finally {
            this.parseState.pop();
        }

    }
}

// 具体解析Property value
public Object parsePropertyValue(Element ele, BeanDefinition bd, String propertyName) {
    // ... ...
    // 处理引用
    if (hasRefAttribute) {
        String refName = ele.getAttribute("ref");
        if (!StringUtils.hasText(refName)) {
            this.error(elementName + " contains empty 'ref' attribute", ele);
        }

        RuntimeBeanReference ref = new RuntimeBeanReference(refName);
        ref.setSource(this.extractSource(ele));
        return ref;
    // 处理值
    } else if (hasValueAttribute) {
        TypedStringValue valueHolder = new TypedStringValue(ele.getAttribute("value"));
        valueHolder.setSource(this.extractSource(ele));
        return valueHolder;
    // 处理其它子类型, 如:array list set map等
    } else if (subElement != null) {
        return this.parsePropertySubElement(subElement, bd);
    } else {
        this.error(elementName + " must specify a ref or value", ele);
        return null;
    }
}
  • 10、注册:BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, this.getReaderContext().getRegistry())
public static void registerBeanDefinition(BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry) throws BeanDefinitionStoreException {
    String beanName = definitionHolder.getBeanName();
    // 看重点
    registry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition());
    String[] aliases = definitionHolder.getAliases();
    if (aliases != null) {
        // ... ...
    }
}
  • 10、重点

private final Map<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap();

public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition) throws BeanDefinitionStoreException {
    // ... ...
    if (beanDefinition instanceof AbstractBeanDefinition) {
        // ... ...
    }

    Map var3 = this.beanDefinitionMap;
    synchronized(this.beanDefinitionMap) {
        Object oldBeanDefinition = this.beanDefinitionMap.get(beanName);
        if (oldBeanDefinition != null) {
            // ... ...
        } else {
            // ... ...
        }
        // 实质:以beanName为key, beanDefinition为value, 把BeanDefinition的实例put进BeanFactory中
        this.beanDefinitionMap.put(beanName, beanDefinition);
        this.resetBeanDefinition(beanName);
    }
}

猜你喜欢

转载自blog.csdn.net/qq_34560242/article/details/80929853
今日推荐