浅谈Spring(叁)——IoC容器初始化

在上一篇文章中,我们主要讲了BeanFactory和ApplicationContext之间的关系,并且看了一部分的源码
本文将顺着上一篇文章的内容,浅谈 IoC容器初始化的过程。


IoC初始化大概可以分为三个部分:
IoC的容器初始化大体可以分为三个部分:定位、加载和注册
定位:读取资源配置,包括import 、url、classpath
加载:解析配置文件,组装beanDefinition
注册:把beanDefinition对象放入IoC容器中

整个流程的流程图如下:
https://www.processon.com/view/link/5b66825de4b0555b39d4205d


我们从ApplicationContext开始,以其实现类ClassPathXmlApplicationContext为例
其一构造函数为

public ClassPathXmlApplicationContext(
            String[] configLocations, boolean refresh, @Nullable ApplicationContext parent)
            throws BeansException {

        super(parent);
        setConfigLocations(configLocations);
        if (refresh) {
            refresh();
        }
    }

其中refresh()方法即为整个IoC容器初始化时最核心的方法,该方法顾名思义是刷新容器,并且触发容器的初始化过程。具体的方法在AbstractApplicationContext中定义:

@Override
    public void refresh() throws BeansException, IllegalStateException {
        synchronized (this.startupShutdownMonitor) {
            // 设置Spring容器的启动时间,撤销关闭状态,开启活跃状态。
                      //初始化属性源信息(Property)
                    // 验证环境信息里一些必须存在的属性
            prepareRefresh();

            // 单例创建 beanFactory 加载所有的xml配置的bean
            ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

            // 从Spring容器获取BeanFactory(Spring Bean容器)并进行相关的设置为后续的使用做准备 
            prepareBeanFactory(beanFactory);

            try {
                // 子类的后处理,不同容器不一样 大致有添加后处理器、忽略依赖接口 
                postProcessBeanFactory(beanFactory);

                // 用默认的BeanFactoryPostProcessor加载其余的BeanFactoryPostProcessor
                        //再处理完成所有的BeanFactoryPostProcessor
                invokeBeanFactoryPostProcessors(beanFactory);

                // 将beanPostProcessor关联到容器
                registerBeanPostProcessors(beanFactory);

                // Initialize message source for this context.
                initMessageSource();

                // 初始化事件发送器
                initApplicationEventMulticaster();

                // 每个子类可以重写的部分  比如说SpringBoot的容器在此创建了一个Tomcat的类
                onRefresh();

                // 关联所有的listener
                registerListeners();

                // 实例化BeanFactory中已经被注册但是未实例化的所有实例(懒加载的不需要实例化)。
//比如invokeBeanFactoryPostProcessors方法中根据各种注解解析出来的类,在这个时候都会被初始化。
//实例化的过程各种BeanPostProcessor开始起作用。

                finishBeanFactoryInitialization(beanFactory);

                // Last step: publish corresponding event.
                finishRefresh();
            }

            catch (BeansException ex) {
                if (logger.isWarnEnabled()) {
                    logger.warn("Exception encountered during context initialization - " +
                            "cancelling refresh attempt: " + ex);
                }

                // Destroy already created singletons to avoid dangling resources.
                destroyBeans();

                // Reset 'active' flag.
                cancelRefresh(ex);

                // Propagate exception to caller.
                throw ex;
            }

            finally {
                // Reset common introspection caches in Spring's core, since we
                // might not ever need metadata for singleton beans anymore...
                resetCommonCaches();
            }
        }
    }

整个过程是由synchronized 锁住的,我们先来分析第二行,注释写的很清楚,这一行的作用就是告诉底层刷新beanFactory的。

// Tell the subclass to refresh the internal bean factory.
            ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

其中

protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
        //销毁上一个BeanFactory,并初始化一个新的BeanFactory
                refreshBeanFactory();
        ConfigurableListableBeanFactory beanFactory = getBeanFactory();
        if (logger.isDebugEnabled()) {
            logger.debug("Bean factory for " + getDisplayName() + ": " + beanFactory);
        }
        return beanFactory;
    }

refreshBeanFactory方法的定义在AbstractRefreshableApplicationContext中:

@Override
    protected final void refreshBeanFactory() throws BeansException {
    //如果存在beanFactory,则销毁   
        if (hasBeanFactory()) {
            destroyBeans();
            closeBeanFactory();
        }
        try {
           //创建beanFactory并设置属性
            DefaultListableBeanFactory beanFactory = createBeanFactory();
            beanFactory.setSerializationId(getId());
            customizeBeanFactory(beanFactory);
           //读取beanDefinitions  
            loadBeanDefinitions(beanFactory);
            synchronized (this.beanFactoryMonitor) {
                this.beanFactory = beanFactory;
            }
        }
        catch (IOException ex) {
            throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
        }
    }

以xml配置为例,此处的loadBeanDefinitions 一路调用到了AbstractXmlApplicationContent

/**
     * 通过XmlBeanDefinitionReader 读取bean definition.
     * @see org.springframework.beans.factory.xml.XmlBeanDefinitionReader
     * @see #initBeanDefinitionReader
     * @see #loadBeanDefinitions
     */
    @Override
    protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
        // 为给定的BeanFactory创建一个新的XmlBeanDefinitionReader.
        XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);

        // 使用当前容器的资源读取环境(resource loading environment)
        // 配置bean definition reader
        beanDefinitionReader.setEnvironment(this.getEnvironment());
        //为Bean读取器设置资源加载器,
        // AbstractXmlApplicationContext的祖先父类AbstractApplicationContext继承DefaultResourceLoader,
        // 因此,容器本身也是一个资源加载器
        // 所以,这个资源加载器由始至终都是容器自身
        beanDefinitionReader.setResourceLoader(this);
        beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));

        // 初始化beandefinitionReader.
        initBeanDefinitionReader(beanDefinitionReader);
        //读取bean definitions
        loadBeanDefinitions(beanDefinitionReader);
    }

loadBeanDefinitions最终调用的是XmlBeanDefinitionReader中的doLoadBeanDefinition 方法。

protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource)
            throws BeanDefinitionStoreException {
        try {
          //利用DocumentLoader加载对应的文档
            Document doc = doLoadDocument(inputSource, resource);
        //  注册给定DOM文档中包含的bean定义
            return registerBeanDefinitions(doc, resource);
        }
        catch (BeanDefinitionStoreException ex) {
            throw ex;
        }
        catch (SAXParseException ex) {
            throw new XmlBeanDefinitionStoreException(resource.getDescription(),
                    "Line " + ex.getLineNumber() + " in XML document from " + resource + " is invalid", ex);
        }
        catch (SAXException ex) {
            throw new XmlBeanDefinitionStoreException(resource.getDescription(),
                    "XML document from " + resource + " is invalid", ex);
        }
        catch (ParserConfigurationException ex) {
            throw new BeanDefinitionStoreException(resource.getDescription(),
                    "Parser configuration exception parsing XML from " + resource, ex);
        }
        catch (IOException ex) {
            throw new BeanDefinitionStoreException(resource.getDescription(),
                    "IOException parsing XML document from " + resource, ex);
        }
        catch (Throwable ex) {
            throw new BeanDefinitionStoreException(resource.getDescription(),
                    "Unexpected exception parsing XML document from " + resource, ex);
        }
    }

registerBeanDefinition方法最终调用的是DefaultBeanDefintionDocumentReader中的doRegisterBeanDefinitions

/**
     * Register each bean definition within the given root {@code } element.
     */
    protected void doRegisterBeanDefinitions(Element root) {
        // Any nested  elements will cause recursion in this method. In
        // order to propagate and preserve  default-* attributes correctly,
        // keep track of the current (parent) delegate, which may be null. Create
        // the new (child) delegate with a reference to the parent for fallback purposes,
        // then ultimately reset this.delegate back to its original (parent) reference.
        // this behavior emulates a stack of delegates without actually necessitating one.
        BeanDefinitionParserDelegate parent = this.delegate;
        this.delegate = createDelegate(getReaderContext(), root, parent);

        if (this.delegate.isDefaultNamespace(root)) {
            String profileSpec = root.getAttribute(PROFILE_ATTRIBUTE);
            if (StringUtils.hasText(profileSpec)) {
                String[] specifiedProfiles = StringUtils.tokenizeToStringArray(
                        profileSpec, BeanDefinitionParserDelegate.MULTI_VALUE_ATTRIBUTE_DELIMITERS);
                if (!getReaderContext().getEnvironment().acceptsProfiles(specifiedProfiles)) {
                    if (logger.isInfoEnabled()) {
                        logger.info("Skipped XML bean definition file due to specified profiles [" + profileSpec +
                                "] not matching: " + getReaderContext().getResource());
                    }
                    return;
                }
            }
        }
    /*
    在处理beanDefinition之前,允许通过自定义标签对xml进行拓展
     */
        preProcessXml(root);
    /**
    处理beanDefinition
     */
        parseBeanDefinitions(root, this.delegate);
    /**
     处理BeanDefinition之后,允许通过自定义标签对xml进行拓展
    */  
    postProcessXml(root);

        this.delegate = parent;
    }

其中,parseBeanDefinitions方法为真正处理beanDefinition的方法

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)) {
                         //解析默认元素
                        parseDefaultElement(ele, delegate);
                    }
                    else {
                         //解析自定义元素
                        delegate.parseCustomElement(ele);
                    }
                }
            }
        }
        else {
            delegate.parseCustomElement(root);
        }
    }

其中,parseDefaultElement方法:

private void parseDefaultElement(Element ele, BeanDefinitionParserDelegate delegate) {
        if (delegate.nodeNameEquals(ele, IMPORT_ELEMENT)) {
            importBeanDefinitionResource(ele);
        }
        else if (delegate.nodeNameEquals(ele, ALIAS_ELEMENT)) {
            processAliasRegistration(ele);
        }
        else if (delegate.nodeNameEquals(ele, BEAN_ELEMENT)) {
            processBeanDefinition(ele, delegate);
        }
        else if (delegate.nodeNameEquals(ele, NESTED_BEANS_ELEMENT)) {
            // recurse
            doRegisterBeanDefinitions(ele);
        }
    }

我们这里解析的是bean,因此进入processBeanDefinition方法

protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) {
        BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);
        if (bdHolder != null) {
            bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);
            try {
                // Register the final decorated instance.
                BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry());
            }
            catch (BeanDefinitionStoreException ex) {
                getReaderContext().error("Failed to register bean definition with name '" +
                        bdHolder.getBeanName() + "'", ele, ex);
            }
            // Send registration event.
            getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder));
        }
    }

之后进入的是BeanDefinitionUtilsregisterBeanDefinition方法

public static void registerBeanDefinition(
            BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry)
            throws BeanDefinitionStoreException {

        // Register bean definition under primary name.
        String beanName = definitionHolder.getBeanName();
        registry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition());

        // Register aliases for bean name, if any.
        String[] aliases = definitionHolder.getAliases();
        if (aliases != null) {
            for (String alias : aliases) {
                registry.registerAlias(beanName, alias);
            }
        }
    }

最后的最后,我们又到了DefaultListableBeanFactory之中,相信看过我上一篇博客的人应该对这个已经很熟悉了

@Override
    public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition)
            throws BeanDefinitionStoreException {

        Assert.hasText(beanName, "Bean name must not be empty");
        Assert.notNull(beanDefinition, "BeanDefinition must not be null");

        if (beanDefinition instanceof AbstractBeanDefinition) {
            try {
                ((AbstractBeanDefinition) beanDefinition).validate();
            }
            catch (BeanDefinitionValidationException ex) {
                throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName,
                        "Validation of bean definition failed", ex);
            }
        }

        BeanDefinition oldBeanDefinition;

        oldBeanDefinition = this.beanDefinitionMap.get(beanName);
        if (oldBeanDefinition != null) {
            if (!isAllowBeanDefinitionOverriding()) {
                throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName,
                        "Cannot register bean definition [" + beanDefinition + "] for bean '" + beanName +
                        "': There is already [" + oldBeanDefinition + "] bound.");
            }
            else if (oldBeanDefinition.getRole() < beanDefinition.getRole()) {
                // e.g. was ROLE_APPLICATION, now overriding with ROLE_SUPPORT or ROLE_INFRASTRUCTURE
                if (this.logger.isWarnEnabled()) {
                    this.logger.warn("Overriding user-defined bean definition for bean '" + beanName +
                            "' with a framework-generated bean definition: replacing [" +
                            oldBeanDefinition + "] with [" + beanDefinition + "]");
                }
            }
            else if (!beanDefinition.equals(oldBeanDefinition)) {
                if (this.logger.isInfoEnabled()) {
                    this.logger.info("Overriding bean definition for bean '" + beanName +
                            "' with a different definition: replacing [" + oldBeanDefinition +
                            "] with [" + beanDefinition + "]");
                }
            }
            else {
                if (this.logger.isDebugEnabled()) {
                    this.logger.debug("Overriding bean definition for bean '" + beanName +
                            "' with an equivalent definition: replacing [" + oldBeanDefinition +
                            "] with [" + beanDefinition + "]");
                }
            }
            this.beanDefinitionMap.put(beanName, beanDefinition);
        }
        else {
            if (hasBeanCreationStarted()) {
                // Cannot modify startup-time collection elements anymore (for stable iteration)
                synchronized (this.beanDefinitionMap) {
                    this.beanDefinitionMap.put(beanName, beanDefinition);
                    List updatedDefinitions = new ArrayList<>(this.beanDefinitionNames.size() + 1);
                    updatedDefinitions.addAll(this.beanDefinitionNames);
                    updatedDefinitions.add(beanName);
                    this.beanDefinitionNames = updatedDefinitions;
                    if (this.manualSingletonNames.contains(beanName)) {
                        Set updatedSingletons = new LinkedHashSet<>(this.manualSingletonNames);
                        updatedSingletons.remove(beanName);
                        this.manualSingletonNames = updatedSingletons;
                    }
                }
            }
            else {
                // Still in startup registration phase
                this.beanDefinitionMap.put(beanName, beanDefinition);
                this.beanDefinitionNames.add(beanName);
                this.manualSingletonNames.remove(beanName);
            }
            this.frozenBeanDefinitionNames = null;
        }

        if (oldBeanDefinition != null || containsSingleton(beanName)) {
            resetBeanDefinition(beanName);
        }
    }

这一段代码中的核心,就是以下代码:


synchronized (this.beanDefinitionMap) {
                    this.beanDefinitionMap.put(beanName, beanDefinition);
                    List updatedDefinitions = new ArrayList<>(this.beanDefinitionNames.size() + 1);
                    updatedDefinitions.addAll(this.beanDefinitionNames);
                    updatedDefinitions.add(beanName);
                    this.beanDefinitionNames = updatedDefinitions;
                    if (this.manualSingletonNames.contains(beanName)) {
                        Set updatedSingletons = new LinkedHashSet<>(this.manualSingletonNames);
                        updatedSingletons.remove(beanName);
                        this.manualSingletonNames = updatedSingletons;
                    }
                }

其中, beanDefinitionMap就是所谓的IoC容器,其具体定义为:

/** Map of bean definition objects, keyed by bean name */
    //传说中的IoC容器
    private final Map beanDefinitionMap = new ConcurrentHashMap<>(256);

BeanDefinition就是类的具体信息。

你可能感兴趣的:(浅谈Spring(叁)——IoC容器初始化)