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 条评论
登录 后参与评论

相关文章

来自专栏JadePeng的技术博客

基于spring security 实现前后端分离项目权限控制

前后端分离的项目,前端有菜单(menu),后端有API(backendApi),一个menu对应的页面有N个API接口来支持,本文介绍如何基于spring se...

680
来自专栏wannshan(javaer,RPC)

Spring 事件传播机制分析

Spring4.0.4 Spring 事件机制采用的是观察者模型(又叫订阅发布模型) 有以下角色 ? 这里,观察者就是监听者,被观察者就是事件对象。 事件发布流...

31710
来自专栏Java架构沉思录

Spring Boot是如何实现自动配置的

Spring Boot 是 Spring 旗下众多的子项目之一,其理念是约定优于配置,它通过实现了自动配置(大多数用户平时习惯设置的配置作为默认配置)的功能来为...

903
来自专栏ASP.NET MVC5 后台权限管理系统

ASP.NET MVC5+EF6+EasyUI 后台管理系统(53)-工作流设计-我的批阅

前言:由于工作原因工作流一直没时间更新,虽然没有更新,但是批阅和申请差不多,改变一下数据的状态字段就行,有几个园友已经率先完成了 说句实话,一个工作流用文章表达...

27610
来自专栏java达人

SpringBoot编写自定义的starter

作者:Format 来源:http://fangjian0423.github.io/2016/11/16/springboot-custom-starter/...

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

fms4 p2p:图片分享

这其实是http://www.flashrealtime.com/file-share-object-replication-flash-p2p/ 中关于文件分...

1827
来自专栏java、Spring、技术分享

Spring Import 三种用法与源码解读

  最近在看Spring Cloud相关的源码,每次引入一个新的starter,发现都会加一些enable的注解,比如:@EnableDiscoveryClie...

783
来自专栏后端之路

跨域二三事之options请求

背景 今天小伙伴问了一个比较奇怪的问题 在某个子系统中通过跨域请求发现POST请求无法正常拿到cookie导致报错 我们从代码来分析一下原因 思路 最重要的永...

3718
来自专栏battcn

Spring解密 - XML解析 与 Bean注册

DefaultListableBeanFactory 是 Spring 注册及加载 bean 的默认实现,整个 SpringIoc模板中它可以称得上 始祖。

753
来自专栏Java3y

Mybatis【与Spring整合】

Mybatis第五篇【Mybatis与Spring整合】 既然我们已经学了Mybatis的基本开发了,接下来就是Mybatis与Spring的整合了! 以下使用...

2304

扫码关注云+社区