Spring IOC容器分析(4) -- bean创建获取完整流程

上节探讨了Spring IOC容器中getBean方法,下面我们将自行编写测试用例,深入跟踪分析bean对象创建过程。

测试环境创建

测试示例代码如下:

package org.springframework.context.mytests;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class ApplicationContextTest {

    @Test
    public void testApplicationContext() {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");
        System.out.println("numbers: " + applicationContext.getBeanDefinitionCount());
        ((Worker)applicationContext.getBean("worker")).work();
    }
}

应用ClassPathXmlApplicationContext加载解析xml文件,xml配置文件如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.3.xsd">
    <bean id="worker" class="org.springframework.context.mytests.Worker"></bean>
</beans>

bean Worker代码如下:

package org.springframework.context.mytests;

public class Worker {
    public void work(){
        System.out.println("I am working");
    }
}

在IDE中对测试文件打断点,进入Debug模式,一步一步跟随程序跟踪bean创建过程。

源码跟踪

跟踪断点,进入ClassPathXmlApplicationContext源码,如下所示:

package org.springframework.context.support;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.util.Assert;

public class ClassPathXmlApplicationContext extends AbstractXmlApplicationContext {

    ......
      
    public ClassPathXmlApplicationContext(String configLocation) throws BeansException {
        this(new String[] {configLocation}, true, null);
    }

    ......

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

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

    ......
}

ClassPathXmlApplicationContex中都是构造器方法,表明加载解析xml文件的操作都是在实例化阶段完成的。以上是部分源码片段,在本测试中,调用第一个构造器初始化,但其实质是调用第二个构造器。从源码可以发现,第二个构造器实际上完成了两个主要功能:

  1. setConfigLocations(configLocations),设置应用上下文的配置文件路径,如果没有设置,便会使用默认路径
  2. refresh(),IOC容器初始化入口

通过查找定位发现:setConfigLocations(configLocations)是继承于AbstractRefreshableConfigApplicationContext抽象类,其源码如下:

    public void setConfigLocations(String... locations) {
        if (locations != null) {
            Assert.noNullElements(locations, "Config locations must not be null");
            this.configLocations = new String[locations.length];
            for (int i = 0; i < locations.length; i++) {
                this.configLocations[i] = resolvePath(locations[i]).trim();
            }
        }
        else {
            this.configLocations = null;
        }
    }

可以看到setConfigLocations方法获取定位信息首先需要调用resolvePath方法对路径进行预处理。

refresh方法是继承于AbstractApplicationContext抽象类,是在接口ConfigurableApplicationContext中定义的。其在抽象类中源码如下:

    @Override
    public void refresh() throws BeansException, IllegalStateException {
        synchronized (this.startupShutdownMonitor) {
            // Prepare this context for refreshing.
            prepareRefresh();

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

            // Prepare the bean factory for use in this context.
            prepareBeanFactory(beanFactory);

            try {
                // Allows post-processing of the bean factory in context subclasses.
                postProcessBeanFactory(beanFactory);

                // Invoke factory processors registered as beans in the context.
                invokeBeanFactoryPostProcessors(beanFactory);

                // Register bean processors that intercept bean creation.
                registerBeanPostProcessors(beanFactory);

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

                // Initialize event multicaster for this context.
                initApplicationEventMulticaster();

                // Initialize other special beans in specific context subclasses.
                onRefresh();

                // Check for listener beans and register them.
                registerListeners();

                // Instantiate all remaining (non-lazy-init) singletons.
                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();
            }
        }
    }

refresh方法大致描述了Spring IOC容器的初始化过程,第一步prepareRefresh主要是做一些准备工作,如准备应用环境、设置启动时间、设置属性源初始化标志等。重点看第二步ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory(),这一步是获取更新后的子类Bean工厂。其源码如下:

    /**
     * Tell the subclass to refresh the internal bean factory.
     * @return the fresh BeanFactory instance
     * @see #refreshBeanFactory()
     * @see #getBeanFactory()
     */
    protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
        refreshBeanFactory();
        ConfigurableListableBeanFactory beanFactory = getBeanFactory();
        if (logger.isDebugEnabled()) {
            logger.debug("Bean factory for " + getDisplayName() + ": " + beanFactory);
        }
        return beanFactory;
    }

其内部有两个方法refreshBeanFactory()getBeanFactory(),这两个方法均为抽象方法,如下所示:

    protected abstract void refreshBeanFactory() throws BeansException, IllegalStateException;

    public abstract ConfigurableListableBeanFactory getBeanFactory() throws IllegalStateException;

查找子类发现,这两个方法均在子类AbstractRefreshableApplicationContext中实现,该类仍然是抽象类。先来看refreshBeanFactory方法实现:

    @Override
    protected final void refreshBeanFactory() throws BeansException {
        if (hasBeanFactory()) {
            destroyBeans();
            closeBeanFactory();
        }
        try {
            DefaultListableBeanFactory beanFactory = createBeanFactory();
            beanFactory.setSerializationId(getId());
            customizeBeanFactory(beanFactory);
            loadBeanDefinitions(beanFactory);
            synchronized (this.beanFactoryMonitor) {
                this.beanFactory = beanFactory;
            }
        }
        catch (IOException ex) {
            throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
        }
    }

该方法先判断是否存在BeanFactory,若存在则直接销毁原BeanFactory,先销毁工厂中的Beans,再关闭工bean厂。之后创建新的Bean工厂,其方法为createBeanFactory,如下所示:

    protected DefaultListableBeanFactory createBeanFactory() {
        return new DefaultListableBeanFactory(getInternalParentBeanFactory());
    }

从函数返回值可以看出,重新创建的Bean工厂是默认的bean工厂DefaultListableBeanFactory类型。创建完新的bean工厂后便会根据上下文进行初始化(customizeBeanFactory),加载bean定义(loadBeanDefinitions)。其中,loadBeanDefinitions为抽象方法,如下所示:

    protected abstract void loadBeanDefinitions(DefaultListableBeanFactory beanFactory)
            throws BeansException, IOException;

该方法具体实现在AbstractXmlApplicationContext类中,该类仍然是一个抽象类,实现如下:

    @Override
    protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
        // Create a new XmlBeanDefinitionReader for the given BeanFactory.
        XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);

        // Configure the bean definition reader with this context's
        // resource loading environment.
        beanDefinitionReader.setEnvironment(this.getEnvironment());
        beanDefinitionReader.setResourceLoader(this);
        beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));

        // Allow a subclass to provide custom initialization of the reader,
        // then proceed with actually loading the bean definitions.
        initBeanDefinitionReader(beanDefinitionReader);
        loadBeanDefinitions(beanDefinitionReader);
    }

阅读源码发现,方法内部是采用XmlBeanDefinitionReader来读取加载bean对象。通过追踪源码,发现XmlBeanDefinitionReader最终调用loadBeanDefinitions方法来读取加载bean,具体实现如下:

    public int loadBeanDefinitions(EncodedResource encodedResource) throws BeanDefinitionStoreException {
        Assert.notNull(encodedResource, "EncodedResource must not be null");
        if (logger.isInfoEnabled()) {
            logger.info("Loading XML bean definitions from " + encodedResource.getResource());
        }

        Set<EncodedResource> currentResources = this.resourcesCurrentlyBeingLoaded.get();
        if (currentResources == null) {
            currentResources = new HashSet<EncodedResource>(4);
            this.resourcesCurrentlyBeingLoaded.set(currentResources);
        }
        if (!currentResources.add(encodedResource)) {
            throw new BeanDefinitionStoreException(
                    "Detected cyclic loading of " + encodedResource + " - check your import definitions!");
        }
        try {
            InputStream inputStream = encodedResource.getResource().getInputStream();
            try {
                InputSource inputSource = new InputSource(inputStream);
                if (encodedResource.getEncoding() != null) {
                    inputSource.setEncoding(encodedResource.getEncoding());
                }
                return doLoadBeanDefinitions(inputSource, encodedResource.getResource());
            }
            finally {
                inputStream.close();
            }
        }
        catch (IOException ex) {
            throw new BeanDefinitionStoreException(
                    "IOException parsing XML document from " + encodedResource.getResource(), ex);
        }
        finally {
            currentResources.remove(encodedResource);
            if (currentResources.isEmpty()) {
                this.resourcesCurrentlyBeingLoaded.remove();
            }
        }
    }

到此,应该明白了IOC容器初始化bean工厂、加载bean对象的大致过程了。现在回头再来看obtainFreshBeanFactory方法中的另一个方法getBeanFactory方法。该方法在子类AbstractRefreshableApplicationContext中实现就相对简单写,如下所示:

    @Override
    public final ConfigurableListableBeanFactory getBeanFactory() {
        synchronized (this.beanFactoryMonitor) {
            if (this.beanFactory == null) {
                throw new IllegalStateException("BeanFactory not initialized or already closed - " +
                        "call 'refresh' before accessing beans via the ApplicationContext");
            }
            return this.beanFactory;
        }
    }

到此为止,Spring IOC容器加载机制探讨基本上告一段落了。通过对源码分析,对Spring IOC机制能有一个大致的了解:1、解析、定位、加载xml配置文件;2、提取配置文件内容;3、新建bean工厂;4、创建Bean定义,并放入map中存储。通过追踪源码,也深刻体会到了spring对设计模式的应用。

下一节将进入对Spring另一大杀器的探讨,Spring-AOP

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏james大数据架构

Android之assets资源

assets目录下存放的原生资源文件,通过getAssets()方法获取. 使用: InputStream inputStream; t...

1778
来自专栏冰枫

Spring容器初始化完成的回调方法

我们可能经常会碰到一些奇奇怪怪的需求,比如在IOC容器初始化完成前实例化一些bean,bean的初始化回调等等等。今天来讲一下如何实现Spring IOC容器如...

65418
来自专栏Java编程技术

常用开源框架扩展清单之原理

评价一个框架是否是优秀的,其中必有一点是该框架是否留足了可扩展的接口。我们在实际做项目中很多情况下就是基于某某框架,然后在这个框架留出的扩展接口上进行业务开发,...

1485
来自专栏菩提树下的杨过

Spring 4.0.2 学习笔记(1) - 最基本的注入

1、 添加maven支持 <dependency> <groupId>org.springframework</grou...

1936
来自专栏石奈子的Java之路

原 SpringBoot 2.0 系列00

1234
来自专栏mukekeheart的iOS之旅

iOS学习——布局利器Masonry框架源码深度剖析

  iOS开发过程中很大一部分内容就是界面布局和跳转,iOS的布局方式也经历了 显式坐标定位方式 --> autoresizingMask --> iOS 6....

4019
来自专栏用户画像

Spring AOP的三种实现方式

参考:https://docs.spring.io/spring/docs/current/spring-framework-reference/core.ht...

761
来自专栏Java Edge

@Autowired 与@Resource之争

31510
来自专栏栗霖积跬步之旅

Spring基础知识之基于注解的AOP

背景概念:   1)横切关注点:散布在应用中多处的功能称为横切关注点   2)通知(Advice):切面完成的工作。通知定了了切面是什么及何时调用。     5...

18910
来自专栏javathings

ApplicationListener 和@EventListener 注解实现事件监听

对于 Spring 容器的一些事件,可以监听并且触发相应的方法。通常的方法有 2 种,ApplicationListener 接口和@EventListener...

1773

扫码关注云+社区