Spring源码分析——IOC容器

论坛 期权论坛 脚本     
匿名网站用户   2020-12-21 07:58   26   0

1、IOC容器的概念

理解IOC容器的概念之前首先需要了解依赖翻转(又称依赖倒置)的概念

许多复杂的应用都是通过多个类之间的彼此合作实现业务逻辑的,这使得每个对象都需要管理自己与其合作对象的依赖,而如果这个过程如果交给对象自身实现将会导致代码的耦合度过高。因此出现了依赖反转的概念

依赖反转

将对象间的依赖关系交由框架或者ioc容器实现与维护,从而在降低代码耦合度的同时提高代码的可测试性。这就叫做对象的依赖反转

ioc容器的概念也就呼之欲出

在Spring中,ioc容器是实现这个模式的载体。它可以在对象生成或初始化阶段直接将数据注入到对象中,也可以将对象引用注入到对象数据域并且这个过程是可递归的,对象被逐层注入。这种方案将对象间的依赖关系逐层建立起来,简化了对象的依赖管理,在很大程度上简化了面向对象系统的复杂性。

既然对于IOC容器有了一个简单的了解,那么下面来探究一下Spring中IOC容器的实现。


2、Spring中两种IOC容器的实现与区别

在Spring Ioc容器的设计中有两个主要的容器系列,一个是实现BeanFactory接口的简单容器系列,这系列容器只实现了容器的基本功能,而另一个是ApplicationContext应用上下文,它作为高级形态的IOC容器在简单容器的基础上增加了许多面向框架的特性,同时对应用环境做了适配因此使用更加广泛。

spring ioc接口设计图
在这里插入图片描述
可以看见ApplicationContext接口在继承了ListableFactory与HierarchicalaBeanFactory这两个BeanFactory接口的基础上,还继承了一系列诸如ResourcePatternResolver(继承自core模块的ResourceLoader接口)的工具类型的接口,以此实现自己更加高级的特性。下面分别介绍spring中这两个ioc容器的具体实现。

2.1 BeanFactory

BeanFactory接口指定了ioc容器实现的具体功能规范,接口的声明如下
BeanFactory<interface>
在这里插入图片描述
可以看到声明的是一些获取容器中Bean,Bean类型以及Bean的生命周期的接口。

在这些Spring提供的基本接口定义与实现的基础之上,Spring通过定义BeanDefination来管理基于Spring应用的各种对象以及对象间的各种依赖关系。
对于ioc容器来说,BeanDefination就是对依赖反转模式中管理的依赖关系的数据抽象,是容器实现依赖反转的核心数据结构,B依赖反转功能都是围绕对这个BeanDefination的处理完成的。对于BeanDefination的具体说明请移步附录部分。

BeanFactory的应用场景
BeanFactory接口定义了IOC容器实现的基本形式,这是我们实现IOC容器应该遵守的最底层的编程规范,定义了ioc容器的基本轮廓,虽然远不如ApplicationContext系列容器的功能齐全,但是在需要高度自由化定制ioc容器是会是更好的选择。

BeanFactory容器的设计原理
Spring提供了一系列BeanFactory的实现供开发人员使用,我们以一个典型的XmlBeanFactory的实现说明BeanFactory类型的ioc容器的设计原理。
XmlBeanFactory的UML类图
在这里插入图片描述

从类图中可以很XmlBeanFactory继承了DefaultListableFactory类,而这个类实际上包含了基本FactoryBean所具有的重要功能,是很多地方都会使用的容器系列的一个基本产品。

XmlBeanFactory在继承了DefaultListableFactory的同时增加了读取以XML方式定的BeanDefination的功能,而这个读取功能是交由XmlBeanDefinitionReader类完成的。

public class XmlBeanFactory extends DefaultListableBeanFactory {

 private final XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(this);

可以看到在类的头部就声明了这个Reader,实际上Spring提供了一个BeanDefinationReader接口,而这个接口的实现类定义了各种途径读取BeanDefination的实现。
BeanDefinationReader接口
在这里插入图片描述

这个接口有以下几个实现
在这里插入图片描述

现在我们可以来关注XmlBeanFactory本身

public class XmlBeanFactory extends DefaultListableBeanFactory {

 private final XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(this);


 /**
  * Create a new XmlBeanFactory with the given resource,
  * which must be parsable using DOM.
  * @param resource XML resource to load bean definitions from
  * @throws BeansException in case of loading or parsing errors
  */
 public XmlBeanFactory(Resource resource) throws BeansException {
  this(resource, null);
 }

 /**
  * Create a new XmlBeanFactory with the given input stream,
  * which must be parsable using DOM.
  * @param resource XML resource to load bean definitions from
  * @param parentBeanFactory parent bean factory
  * @throws BeansException in case of loading or parsing errors
  */
 public XmlBeanFactory(Resource resource, BeanFactory parentBeanFactory) throws BeansException {
  super(parentBeanFactory);
  this.reader.loadBeanDefinitions(resource);
 }

}

可以看到只有两个构造方法,都需要传入Resource类型的对象指定BeanDefination信息的来源,Resource接口定义了获取资源的方法,有以下实现
在这里插入图片描述

以我们常用的ClassPathResource举例

ClaaPathResource resource = new ClassPath("spring-config.xml“);

这样就加载到了定义在spring-config.xml中的BeanDefination源信息。然后交由XmlBeanDefinitionReader对象进行解析(这段逻辑在构造函数的源码中体现的非常清楚)。

弄清楚各个组件的职责后后我们可以直接使用父类DefaultListableBeanFactory初始化IOC容器:

ClaaPathResource resource = new ClassPath("spring-config.xml“);
DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
XmlBeanDefinationReader reader = new XmlBeanDefinationReader(factory);
reader.loadBeanDefinitions(resource);
  1. 创建ioc配置文件的抽象资源,这个抽象资源包含了BeanDefinations的源信息(resource)。
  2. 创建一个BeanFactory
  3. 创建一个BeanDefination的读取器(reader)并通过一个回调配置给factory
  4. 具体的解析过程交由reader类来做,完成所有Bean的载入和注册之后ioc容器即建立完毕,此时口可以直接使用这个容器了(getBean啊之类的)。

2.2 ApplicationContext

首先看一下ApplicationContext基于BeanFactory的基础上为我们提供了哪些附加服务:
在这里插入图片描述

  1. 支持不同的信息源:这个功能由扩展的MessageSource接口实现,这些消息源的扩展功能可以支持国际化的实现。
  2. 访问资源,这一特性体现在对ResourceLoader与Resource接口的支持上(ResourceLoader接口需要实现的主要方法之一就是getResource,另一个是getClassLoader)。这种抽象可以使用户灵活的定义如何获取BeanDefination定义信息,尤其是从不同的IO途径获取。
  3. 支持应用事件,这一特性体现在继承了接口ApplicationEventPublisher上,从而在上下文引入了事件机制,这些事件与bean的什么周期的结合为Bean的管理提供了便利。

ApplicationContext的设计原理
下面我们以常用的FileSystemXmlApplicationContext的实现为例说明ApplicationContext容器的设计原理。
FileSystemXmlApplicationContext类图
在这里插入图片描述
可以看到FileSystemXmlApplicationContext的主要功能以及交由基类AbstractXmlApplicationContext,而基类AbstractXmlApplicationContext的一部分功能交由了更基础的AbstractRefreshableConfigApplicationContext实现。我们主要关注FileSystemXmlApplicationContext自身实现有关的两个功能:

  1. 容器的启动过程
 public FileSystemXmlApplicationContext(
   String[] configLocations, boolean refresh, @Nullable ApplicationContext parent)
   throws BeansException {

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

这里我们需要重点关注的是refresh这个方法,这个是ioc容器启动的真正入口

  1. 对应类名,怎么从文件系统中加载使用xml定义的BeanDefination元信息
 @Override
 protected Resource getResourceByPath(String path) {
  if (path.startsWith("/")) {
   path = path.substring(1);
  }
  return new FileSystemResource(path);
 }

代码很好理解,直接返回了FileSystemResource类型的source作为信息源。

那么接下来研究的就是以refresh方法为入口的ioc容器的初始化过程


3、IOC容器的初始化过程

3.1 总览

ioc容器的初始化入口就是上一节提到的refresh方法,这个启动包含以下几个过程:
Resource定位 -> BeanDefination载入 -> BeanDefination注入

spring将这三个模块分开并使用不同的模块完成。

  1. Resource定位:指对BeanDefination元信息的资源定位,由ResourceLoader模块通过统一的Resource接口完成。
  2. BeanDefination载入:载入过程即将用户定义好的Bean转换成容器内部的数据结构<BeanDefination>。通过BeanDefination这个数据结构附带的各种信息,使得ioc容器可以方便的管理容器中的Bean对象。这个过程交由BeanDefinationReader模块完成。
  3. BeanDefination 注册:注册过程将第二步载入的BeanDefination通过BeanDefinitionRegistry接口(比如我们的 DefaultListableBeanFactory就实现了这个接口)解析成需要的Bean注册到我们的IOC容器中(一个HashMap)。

值得注意的是ioc容器的初始化过程一般不包括bean的依赖注入。事实上依赖注入一般会发生在应用第一次通过getBean接口向容器索要Bean时,这个在下一节会有详细的解释这里不再赘述。现在开始逐个分析这三大过程。

3.2 resource定位

由于ApplicationContext中已经配置了一系列加载不同Resource读取器的实现,所以我们不需要像使用DefaultListableBeanFactory那样手动指定BeanDefinationReader的实现。只需要在ApplicationContext的实现类中重写声明在DefaultResourceLoader中的getResourceByPath方法即可。举几个常见的ApplicationContext的实现

  1. FileSystemXmlApplicationContext:从文件系统载入Resource
 @Override
 protected Resource getResourceByPath(String path) {
  if (path.startsWith("/")) {
   path = path.substring(1);
  }
  return new FileSystemResource(path);
 }
  1. ClassPathXmlApplicationContext:从classpath路径下载入Resource
 @Override
 protected Resource getResourceByPath(String path) {
  return new ClassPathContextResource(path, getClassLoader());
 }
  1. XmlWebApplicationContext:从web容器中载入Resource
 @Override
 protected Resource getResourceByPath(String path) {
  Assert.state(this.servletContext != null, "No ServletContext available");
  return new ServletContextResource(this.servletContext, path);
 }

实际上在这几个类的基类AbstractRefreshableApplicationContext中有一个getResource方法,是这样实现的:

@Override
 public Resource getResource(String location) {
  Assert.notNull(location, "Location must not be null");

  for (ProtocolResolver protocolResolver : this.protocolResolvers) {
   Resource resource = protocolResolver.resolve(location, this);
   if (resource != null) {
    return resource;
   }
  }

  if (location.startsWith("/")) {
   return getResourceByPath(location);
  }
  else if (location.startsWith(CLASSPATH_URL_PREFIX)) {
   return new ClassPathResource(location.substring(CLASSPATH_URL_PREFIX.length()), getClassLoader());
  }
  else {
   try {
    // Try to parse the location as a URL...
    URL url = new URL(location);
    return (ResourceUtils.isFileURL(url) ? new FileUrlResource(url) : new UrlResource(url));
   }
   catch (MalformedURLException ex) {
    // No URL -> resolve as resource path.
    return getResourceByPath(location);
   }
  }
 }

注意这个方法最后调用了子类中重写的getResourceByPath方法。

定位完成后已经为BeanDefination的载入创造了条件,但是具体的数据载入将交由下一步去做。现在让我们继续分析BeanDefination的载入。

3.3 BeanDefination载入

载入过程相当于将我们定义的BeanDefination在ioc容器中转化为一个Spring内部表示的数据结构的过程。下面我们从容器初始化的入口refresh方法进行分析:
AbstractApplicationContext:refresh()

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

   // 相当于调用子类的refreshBeanFactory方法
   ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

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

   try {
    // 设置BeanFactory的后置处理器
    postProcessBeanFactory(beanFactory);

    // 调用后置处理器
    invokeBeanFactoryPostProcessors(beanFactory);

    // 注册Bean的后处理器,在Bean的初始化过程调用
    registerBeanPostProcessors(beanFactory);

    // 对上小文的消息源进行初始化
    initMessageSource();

    // 初始化容器事件机制
    initApplicationEventMulticaster();

    // 初始化其它特殊bean
    onRefresh();

    // 检查监听类型的bean并向容器注册
    registerListeners();

    // 提前实例化所有non-lazy-init单件
    finishBeanFactoryInitialization(beanFactory);

    // 发布容器事件,结束refresh过程
    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方法详细的描述了整个ApplicationContext的初始化过程。
obtainFreshBeanFactory方法最终调用的是子类的refreshBeanFactory实现,在这个方法中创建了BeanFactory,如果之前已经有容器存在则要关闭和销毁以保障refresh后使用的是新建立的容器:
AbstractRefreshableApplicationContext:refreshBeanFactory

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

在这个方法中我们可以很清楚的看到创建了ioc容器后使用该容器启动了对BeanDefinations的载入过程,时序图如下:
在这里插入图片描述

AbstractRefreshableApplicationContext中的loadBeanDefinations是一个抽象方法,
不同子类有不同的实现。我们来看看在AbstractXmlApplicationContext中的方法实现:
AbstractXmlApplicationContext:loadBeanDefinations

 @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);
 }

终于被我们找到了读取器BeanDefinationReader。这个方法中先是使用入参BeanFactory初始化了XmlBeanDefinitionReader,然后为XmlBeanDefinitionReader设置了ResourceLoader数据源(因为ApplicationContext自己实现了该接口所以体现在代码里的入参为this),之后调用initBeanDefinitionReader与loadBeanDefination方法完成载入过程。我们继续跟进loadBeanDefinitions(beanDefinitionReader)方法。
loadBeanDefinitions(beanDefinitionReader)

 protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException {
     //以Resource的方式获取资源位置
  Resource[] configResources = getConfigResources();
  if (configResources != null) {
   reader.loadBeanDefinitions(configResources);
  }

        //以String的形式获取配置文件的位置
  String[] configLocations = getConfigLocations();
  if (configLocations != null) {
   reader.loadBeanDefinitions(configLocations);
  }
 }
 /**
  * Return an array of Resource objects, referring to the XML bean definition
  * files that this context should be built with.
  * <p>The default implementation returns {@code null}. Subclasses can override
  * this to provide pre-built Resource objects rather than location Strings.
  * @return an array of Resource objects, or {@code null} if none
  * @see #getConfigLocations()
  */
 @Nullable
 protected Resource[] getConfigResources() {
  return null;
 }

由于我们是AbstractXmlApplicationContext,所以自然也需要使用XmlBeanDefinationReader,在XmlBeanDefinationReader中loadBeanDefinitions方法是这样实现的:
XmlBeanDefinationReader:loadBeanDefinitions

 @Override
 public int loadBeanDefinitions(Resource... resources) throws BeanDefinitionStoreException {
  Assert.notNull(resources, "Resource array must not be null");
  int counter = 0;
  for (Resource resource : resources) {
   counter += loadBeanDefinitions(resource);
  }

        //统计一共加载了多少BeanDefination
  return counter;
 }

   @Override
 public int loadBeanDefinitions(Resource resource) throws BeanDefinitionStoreException {
  return loadBeanDefinitions(new EncodedResource(resource));
 }

     /**
  * Load bean definitions from the specified XML file.
  * @param encodedResource the resource descriptor for the XML file,
  * allowing to specify an encoding to use for parsing the file
  * @return the number of bean definitions found
  * @throws BeanDefinitionStoreException in case of loading or parsing errors
  */
 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);
  }

  Set<EncodedResource> currentResources = this.resourcesCurrentlyBeingLoaded.get();
  if (currentResources == null) {
   currentResources = new HashSet<>(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();
   }
  }
 }

可以看到loadBeanDefinitions方法中甚至帮我们完成了加载BeanDefination个数的统计,而经过一系列方法调用后也成功从被包装成EncodedResource的resource中获取到了输入流并读取到了数据,而对xml数据的具体解析则是交给doLoadBeanDefinations这个方法来做的:
XmlBeanDefinationReader:doLoadBeanDefinitions

 /**
  * Actually load bean definitions from the specified XML file.
  * @param inputSource the SAX InputSource to read from
  * @param resource the resource descriptor for the XML file
  * @return the number of bean definitions found
  * @throws BeanDefinitionStoreException in case of loading or parsing errors
  * @see #doLoadDocument
  * @see #registerBeanDefinitions
  */
 protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource)
   throws BeanDefinitionStoreException {
  try {
   Document doc = doLoadDocument(inputSource, resource);
   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);
  }
 }

    /**
  * Actually load the specified document using the configured DocumentLoader.
  * @param inputSource the SAX InputSource to read from
  * @param resource the resource descriptor for the XML file
  * @return the DOM Document
  * @throws Exception when thrown from the DocumentLoader
  * @see #setDocumentLoader
  * @see DocumentLoader#loadDocument
  */
 protected Document doLoadDocument(InputSource inputSource, Resource resource) throws Exception {
  return this.documentLoader.loadDocument(inputSource, getEntityResolver(), this.errorHandler,
    getValidationModeForResource(resource), isNamespaceAware());
 }

观察方法调用发现最后xml类型的Document的解析工作委派给了DocumentLoader的实现类DefaultDocumentLoader来做,如何解析document不是我们关注的重点,感兴趣的小伙伴可以自己去研究,我们关心的是解析出document对象后调用的registerBeanDefinitions方法中做了什么
XmlBeanDefinationReader:registerBeanDefinitions

 public int registerBeanDefinitions(Document doc, Resource resource) throws BeanDefinitionStoreException {
  BeanDefinitionDocumentReader documentReader = createBeanDefinitionDocumentReader();
  int countBefore = getRegistry().getBeanDefinitionCount();
  documentReader.registerBeanDefinitions(doc, createReaderContext(resource));
  return getRegistry().getBeanDefinitionCount() - countBefore;
 }

BeanDefination的载入分为两个部分,首先调用XML解析器获得document对象,但此时的document对象并没有按照Spring的Bean规则解析为容器内部对象,而这个解析过程是交由DocumentDefinationBeanReader实现的。使用这个类完成对BeanDefination的处理,处理的结果交由BeanDefinationHolder持有(这个对象不仅持有BeanDefination信息还有一些相关信息如Bean名称,别名集合等)。这个BeanDefinationHolder的生成是通过对document文档树内容的解析生成的,而解析过程交由BeanDefinationParseraDelegate的processBeanDefination方法实现
DefaultBeanDefinitionDocumentReader:registerBeanDefinitions

 @Override
 public void registerBeanDefinitions(Document doc, XmlReaderContext readerContext) {
  this.readerContext = readerContext;
  logger.debug("Loading bean definitions");
  Element root = doc.getDocumentElement();
  doRegisterBeanDefinitions(root);
 }

   protected void doRegisterBeanDefinitions(Element root) {
  // Any nested <beans> elements will cause recursion in this method. In
  // order to propagate and preserve <beans> 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;
    }
   }
  }

  preProcessXml(root);
  parseBeanDefinitions(root, this.delegate);
  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)) {
      parseDefaultElement(ele, delegate);
     }
     else {
      delegate.parseCustomElement(ele);
     }
    }
   }
  }
  else {
   delegate.parseCustomElement(root);
  }
 }

    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);
  }
 }

 /**
  * Process the given bean element, parsing the bean definition
  * and registering it with the registry.
  */
 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));
  }
 }

重点关注processBeanDefination中的这一句代码BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry());。此时已经完成了document向ioc容器内置对象(bdHolder)的解析,下一步就是将解析完成的BeanDefination注册到容器中了。

3.4 BeanDefination注册

首先看BeanDefinitionReaderUtils.registerBeanDefinition这个方法
BeanDefinitionReaderUtils.registerBeanDefinition

 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);
   }
  }
 }

关注registry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition());这一句代码。这里的registry就是我们使用createBeanFactory()创建的DefaultListableBeanFactory。我们现在要根据BeanDefinationHolder对象持有的beanName与别名信息,调用rigistry.registerBeanDefinition方法将BeanDifination注入到BeanFactory的内置集合中(在DefaultListableBeanFactory中就是一个ConcurrentHashMap)。下面我们来看看DefaultListableBeanFactory中的registerBeanDefination是怎么实现的:
DefaultListableBeanFactory:registerBeanDefination()

 @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 existingDefinition = this.beanDefinitionMap.get(beanName);
  if (existingDefinition != null) {
   if (!isAllowBeanDefinitionOverriding()) {
    throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName,
      "Cannot register bean definition [" + beanDefinition + "] for bean '" + beanName +
      "': There is already [" + existingDefinition + "] bound.");
   }
   else if (existingDefinition.getRole() < beanDefinition.getRole()) {
    // e.g. was ROLE_APPLICATION, now overriding with ROLE_SUPPORT or ROLE_INFRASTRUCTURE
    if (logger.isWarnEnabled()) {
     logger.warn("Overriding user-defined bean definition for bean '" + beanName +
       "' with a framework-generated bean definition: replacing [" +
       existingDefinition + "] with [" + beanDefinition + "]");
    }
   }
   else if (!beanDefinition.equals(existingDefinition)) {
    if (logger.isInfoEnabled()) {
     logger.info("Overriding bean definition for bean '" + beanName +
       "' with a different definition: replacing [" + existingDefinition +
       "] with [" + beanDefinition + "]");
    }
   }
   else {
    if (logger.isDebugEnabled()) {
     logger.debug("Overriding bean definition for bean '" + beanName +
       "' with an equivalent definition: replacing [" + existingDefinition +
       "] 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<String> updatedDefinitions = new ArrayList<>(this.beanDefinitionNames.size() + 1);
     updatedDefinitions.addAll(this.beanDefinitionNames);
     updatedDefinitions.add(beanName);
     this.beanDefinitionNames = updatedDefinitions;
     if (this.manualSingletonNames.contains(beanName)) {
      Set<String> 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 (existingDefinition != null || containsSingleton(beanName)) {
   resetBeanDefinition(beanName);
  }
 }

主体逻辑就是根据BeanName将BeanDefination设置到容器内部持有的beanDefinitionMap这个集合中。
注册过程的时序图如下:
在这里插入图片描述
至此我们完成了ioc容器的初始化过程。(可以看到三个过程中的解析与载入过程是最复杂的)此时在使用的ioc容器(这里是DefaultListableBeanFactory)中已经建立起了整个Bean的配置信息,它们都可以在
beanDefinitionMap中被检索与使用。容器的作用就是对这些信息进行处理和维护,因为这些信息是容器建立依赖反转的基础。有了这些基础数据,接下来我们将研究在ioc容器中,依赖注入是如何完成的


4、IOC容器的依赖注入过程

之前提到,在容器的初始化过程并不会进行依赖注入,但是这个说法是有漏洞的,因为只有在不指定bean的lazyinit属性(即默认值为ture时)。才不会提前进行依赖注入。而当lazyinit=false时,容器会在初始化过程中提前调用getBean方法,导致依赖注入发生。下面我们分别分析两种情况下的依赖注入过程。

4.1 lazyinit=true的情况

依赖注入发生的入口方法为getBean,我们阅读以下DefaultListableBeanFactory的源码:
AbstractBeanFactory:getBean

   @Override
   public Object getBean(String name) throws BeansException {
    return doGetBean(name, null, null, false);
   }
   
   protected <T> T doGetBean(final String name, @Nullable final Class<T> requiredType,
     @Nullable final Object[] args, boolean typeCheckOnly) throws BeansException {

    final String beanName = transformedBeanName(name);
    Object bean;

    // 首先试图从缓存中获取singleton类型的bean,因为这种类型的bean不需要重复创建
    Object sharedInstance = getSingleton(beanName);
    if (sharedInstance != null && args == null) {
     if (logger.isDebugEnabled()) {
      if (isSingletonCurrentlyInCreation(beanName)) {
       logger.debug("Returning eagerly cached instance of singleton bean '" + beanName +
         "' that is not fully initialized yet - a consequence of a circular reference");
      }
      else {
       logger.debug("Returning cached instance of singleton bean '" + beanName + "'");
      }
     }
        // 获取FactoryBean的生产结果(FactoryBean.getObject())
     bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
    }

    else {
     // Fail if we're already creating this bean instance:
     // We're assumably within a circular reference.
     if (isPrototypeCurrentlyInCreation(beanName)) {
      throw new BeanCurrentlyInCreationException(beanName);
     }

     // Check if bean definition exists in this factory.
     // 检查BeanDefination是否存在,一致沿着ParentBeanFactory向上查找直到找到根BeanFactory为止
     BeanFactory parentBeanFactory = getParentBeanFactory();
     if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
      // Not found -> check parent.
      String nameToLookup = originalBeanName(name);
      if (parentBeanFactory instanceof AbstractBeanFactory) {
       return ((AbstractBeanFactory) parentBeanFactory).doGetBean(
         nameToLookup, requiredType, args, typeCheckOnly);
      }
      else if (args != null) {
       // Delegation to parent with explicit args.
       return (T) parentBeanFactory.getBean(nameToLookup, args);
      }
      else {
       // No args -> delegate to standard getBean method.
       return parentBeanFactory.getBean(nameToLookup, requiredType);
      }
     }

     if (!typeCheckOnly) {
      markBeanAsCreated(beanName);
     }

     try {
         // 根据beanName获取BeanDefinition
      final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
      checkMergedBeanDefinition(mbd, beanName, args);

      // Guarantee initialization of beans that the current bean depends on.
      // 获取当前bean所依赖的所有bean然后进行注入,注入过程会触发getBean的递归调用直到一个不依赖任何bean的bean出现
      String[] dependsOn = mbd.getDependsOn();
      if (dependsOn != null) {
       for (String dep : dependsOn) {
        if (isDependent(beanName, dep)) {
         throw new BeanCreationException(mbd.getResourceDescription(), beanName,
           "Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
        }
        registerDependentBean(dep, beanName);
        try {
         getBean(dep);
        }
        catch (NoSuchBeanDefinitionException ex) {
         throw new BeanCreationException(mbd.getResourceDescription(), beanName,
           "'" + beanName + "' depends on missing bean '" + dep + "'", ex);
        }
       }
      }

      // Create bean instance.
      // 可以看到创建Singleton类型的bean的方法回调了BeanFactory的createBean()方法
      if (mbd.isSingleton()) {
       sharedInstance = getSingleton(beanName, () -> {
        try {
         return createBean(beanName, mbd, args);
        }
        catch (BeansException ex) {
         // Explicitly remove instance from singleton cache: It might have been put there
         // eagerly by the creation process, to allow for circular reference resolution.
         // Also remove any beans that received a temporary reference to the bean.
         destroySingleton(beanName);
         throw ex;
        }
       });
       bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
      }

               // 创建Proptype类型的bean就要简单很多
      else if (mbd.isPrototype()) {
       // It's a prototype -> create a new instance.
       Object prototypeInstance = null;
       try {
        beforePrototypeCreation(beanName);
        prototypeInstance = createBean(beanName, mbd, args);
       }
       finally {
        afterPrototypeCreation(beanName);
       }
       bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
      }

      else {
       String scopeName = mbd.getScope();
       final Scope scope = this.scopes.get(scopeName);
       if (scope == null) {
        throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
       }
       try {
        Object scopedInstance = scope.get(beanName, () -> {
         beforePrototypeCreation(beanName);
         try {
          return createBean(beanName, mbd, args);
         }
         finally {
          afterPrototypeCreation(beanName);
         }
        });
        bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
       }
       catch (IllegalStateException ex) {
        throw new BeanCreationException(beanName,
          "Scope '" + scopeName + "' is not active for the current thread; consider " +
          "defining a scoped proxy for this bean if you intend to refer to it from a singleton",
          ex);
       }
      }
     }
     catch (BeansException ex) {
      cleanupAfterBeanCreationFailure(beanName);
      throw ex;
     }
    }

    // Check if required type matches the type of the actual bean instance.
    // 对创建的bean进行类型检查,如果没问题此时这个bean就是已经包含了依赖关系的bean了
    if (requiredType != null && !requiredType.isInstance(bean)) {
     try {
      T convertedBean = getTypeConverter().convertIfNecessary(bean, requiredType);
      if (convertedBean == null) {
       throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
      }
      return convertedBean;
     }
     catch (TypeMismatchException ex) {
      if (logger.isDebugEnabled()) {
       logger.debug("Failed to convert bean '" + name + "' to required type '" +
         ClassUtils.getQualifiedName(requiredType) + "'", ex);
      }
      throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
     }
    }
    return (T) bean;
   }

从方法中我们可以看出获取bean的依赖消息靠的是保存在BeanDefinition中的getDependsOn()方法,这个方法会返回一个当前bean依赖的beanName的数组,根据这个数组进行依赖注入。下面看看Singletion类型的Bean创建时回调的createBean()方法
AbstractAutowireCapableBeanFactory:createBean()

/**
    * Central method of this class: creates a bean instance,
    * populates the bean instance, applies post-processors, etc.
    * @see #doCreateBean
    */
   @Override
   protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
     throws BeanCreationException {

    if (logger.isDebugEnabled()) {
     logger.debug("Creating instance of bean '" + beanName + "'");
    }
    RootBeanDefinition mbdToUse = mbd;

    // Make sure bean class is actually resolved at this point, and
    // clone the bean definition in case of a dynamically resolved Class
    // which cannot be stored in the shared merged bean definition.
    Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
    if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
     mbdToUse = new RootBeanDefinition(mbd);
     mbdToUse.setBeanClass(resolvedClass);
    }

    // Prepare method overrides.
    try {
     mbdToUse.prepareMethodOverrides();
    }
    catch (BeanDefinitionValidationException ex) {
     throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
       beanName, "Validation of method overrides failed", ex);
    }

    try {
     // Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
     Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
     if (bean != null) {
      return bean;
     }
    }
    catch (Throwable ex) {
     throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,
       "BeanPostProcessor before instantiation of bean failed", ex);
    }

    try {
     Object beanInstance = doCreateBean(beanName, mbdToUse, args);
     if (logger.isDebugEnabled()) {
      logger.debug("Finished creating instance of bean '" + beanName + "'");
     }
     return beanInstance;
    }
    catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) {
     // A previously detected exception with proper bean creation context already,
     // or illegal singleton state to be communicated up to DefaultSingletonBeanRegistry.
     throw ex;
    }
    catch (Throwable ex) {
     throw new BeanCreationException(
       mbdToUse.getResourceDescription(), beanName, "Unexpected exception during bean creation", ex);
    }
   }

createBean方法又调用了doCreateBean

/**
    * Actually create the specified bean. Pre-creation processing has already happened
    * at this point, e.g. checking {@code postProcessBeforeInstantiation} callbacks.
    * <p>Differentiates between default bean instantiation, use of a
    * factory method, and autowiring a constructor.
    * @param beanName the name of the bean
    * @param mbd the merged bean definition for the bean
    * @param args explicit arguments to use for constructor or factory method invocation
    * @return a new instance of the bean
    * @throws BeanCreationException if the bean could not be created
    * @see #instantiateBean
    * @see #instantiateUsingFactoryMethod
    * @see #autowireConstructor
    */
   protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
     throws BeanCreationException {

    // Instantiate the bean.
    BeanWrapper instanceWrapper = null;
    // 如果是Singleton类型的bean,先将缓存中同名的bean清除
    if (mbd.isSingleton()) {
     instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
    }
    if (instanceWrapper == null) {
       // 创建bean的方法,createBeanInstance
     instanceWrapper = createBeanInstance(beanName, mbd, args);
    }
    final Object bean = instanceWrapper.getWrappedInstance();
    Class<?> beanType = instanceWrapper.getWrappedClass();
    if (beanType != NullBean.class) {
     mbd.resolvedTargetType = beanType;
    }

    // Allow post-processors to modify the merged bean definition.
    synchronized (mbd.postProcessingLock) {
     if (!mbd.postProcessed) {
      try {
       applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
      }
      catch (Throwable ex) {
       throw new BeanCreationException(mbd.getResourceDescription(), beanName,
         "Post-processing of merged bean definition failed", ex);
      }
      mbd.postProcessed = true;
     }
    }

    // Eagerly cache singletons to be able to resolve circular references
    // even when triggered by lifecycle interfaces like BeanFactoryAware.
    boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
      isSingletonCurrentlyInCreation(beanName));
    if (earlySingletonExposure) {
     if (logger.isDebugEnabled()) {
      logger.debug("Eagerly caching bean '" + beanName +
        "' to allow for resolving potential circular references");
     }
     addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
    }

    // Initialize the bean instance.
    // 初始化Bean
    Object exposedObject = bean;
    try {
        // 发生依赖注入的入口方法populateBean
     populateBean(beanName, mbd, instanceWrapper);
     exposedObject = initializeBean(beanName, exposedObject, mbd);
    }
    catch (Throwable ex) {
     if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
      throw (BeanCreationException) ex;
     }
     else {
      throw new BeanCreationException(
        mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
     }
    }

    if (earlySingletonExposure) {
     Object earlySingletonReference = getSingleton(beanName, false);
     if (earlySingletonReference != null) {
      if (exposedObject == bean) {
       exposedObject = earlySingletonReference;
      }
      else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
       String[] dependentBeans = getDependentBeans(beanName);
       Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);
       for (String dependentBean : dependentBeans) {
        if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
         actualDependentBeans.add(dependentBean);
        }
       }
       if (!actualDependentBeans.isEmpty()) {
        throw new BeanCurrentlyInCreationException(beanName,
          "Bean with name '" + beanName + "' has been injected into other beans [" +
          StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +
          "] in its raw version as part of a circular reference, but has eventually been " +
          "wrapped. This means that said other beans do not use the final version of the " +
          "bean. This is often the result of over-eager type matching - consider using " +
          "'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example.");
       }
      }
     }
    }

doCreateBean()方法中与依赖注入密切相关的就是populateBean()与createBeanInstance()了,下面分别看看这两个方法。

AbstractAutowireCapableBeanFactory:createBeanInstance()

protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
  // Make sure bean class is actually resolved at this point.
  Class<?> beanClass = resolveBeanClass(mbd, beanName);

  if (beanClass != null && !Modifier.isPublic(beanClass.getModifiers()) && !mbd.isNonPublicAccessAllowed()) {
   throw new BeanCreationException(mbd.getResourceDescription(), beanName,
     "Bean class isn't public, and non-public access not allowed: " + beanClass.getName());
  }

  Supplier<?> instanceSupplier = mbd.getInstanceSupplier();
  if (instanceSupplier != null) {
   return obtainFromSupplier(instanceSupplier, beanName);
  }

        // 使用工厂模式
  if (mbd.getFactoryMethodName() != null)  {
   return instantiateUsingFactoryMethod(beanName, mbd, args);
  }

  // Shortcut when re-creating the same bean...
  boolean resolved = false;
  boolean autowireNecessary = false;
  if (args == null) {
   synchronized (mbd.constructorArgumentLock) {
    if (mbd.resolvedConstructorOrFactoryMethod != null) {
     resolved = true;
     autowireNecessary = mbd.constructorArgumentsResolved;
    }
   }
  }
  if (resolved) {
   if (autowireNecessary) {
    return autowireConstructor(beanName, mbd, null, null);
   }
   else {
    return instantiateBean(beanName, mbd);
   }
  }

  // 使用构造函数
  Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
  if (ctors != null ||
    mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_CONSTRUCTOR ||
    mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args))  {
   return autowireConstructor(beanName, mbd, ctors, args);
  }

  // No special handling: simply use no-arg constructor.
  return instantiateBean(beanName, mbd);
 }

 protected BeanWrapper instantiateBean(final String beanName, final RootBeanDefinition mbd) {
  try {
   Object beanInstance;
   final BeanFactory parent = this;
   if (System.getSecurityManager() != null) {
    beanInstance = AccessController.doPrivileged((PrivilegedAction<Object>) () ->
      getInstantiationStrategy().instantiate(mbd, beanName, parent),
      getAccessControlContext());
   }
   else {
    beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, parent);
   }
   BeanWrapper bw = new BeanWrapperImpl(beanInstance);
   initBeanWrapper(bw);
   return bw;
  }
  catch (Throwable ex) {
   throw new BeanCreationException(
     mbd.getResourceDescription(), beanName, "Instantiation of bean failed", ex);
  }
 }

在createBeanInstance中创建了Bean包含的java对象,这个对象的创建有很多种方式,已经在注释中说明了。使用哪种生成方式是在BeanDefinition中指定的。另外还可以看到在实例化方法institate中使用的是默认的InstantiateStrategy,而在DefaultListaleBeanFactory只这个生成策略是CglibSubclassingInstantiationStrategy。而不是Java反射。

AbstractAutowireCapableBeanFactory:populateBean()

 /**
  * Populate the bean instance in the given BeanWrapper with the property values
  * from the bean definition.
  * @param beanName the name of the bean
  * @param mbd the bean definition for the bean
  * @param bw the BeanWrapper with bean instance
  */
 protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
  if (bw == null) {
   if (mbd.hasPropertyValues()) {
    throw new BeanCreationException(
      mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
   }
   else {
    // Skip property population phase for null instance.
    return;
   }
  }

  // Give any InstantiationAwareBeanPostProcessors the opportunity to modify the
  // state of the bean before properties are set. This can be used, for example,
  // to support styles of field injection.
  boolean continueWithPropertyPopulation = true;

  if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
   for (BeanPostProcessor bp : getBeanPostProcessors()) {
    if (bp instanceof InstantiationAwareBeanPostProcessor) {
     InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
     if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
      continueWithPropertyPopulation = false;
      break;
     }
    }
   }
  }

  if (!continueWithPropertyPopulation) {
   return;
  }

        // 获取BeanDefinition中定义的property值,为接下来的依赖注入做准备
  PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);

       // 开始依赖注入
       // 先处理自动注入
  if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME ||
    mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
   MutablePropertyValues newPvs = new MutablePropertyValues(pvs);

   // Add property values based on autowire by name if applicable.
   if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME) {
    // 按beanName自动注入
    autowireByName(beanName, mbd, bw, newPvs);
   }

   // Add property values based on autowire by type if applicable.
   if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
    // 按BeanType自动注入
    autowireByType(beanName, mbd, bw, newPvs);
   }

   pvs = newPvs;
  }

  boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
  boolean needsDepCheck = (mbd.getDependencyCheck() != RootBeanDefinition.DEPENDENCY_CHECK_NONE);

  if (hasInstAwareBpps || needsDepCheck) {
   if (pvs == null) {
    pvs = mbd.getPropertyValues();
   }
   PropertyDescriptor[] filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
   if (hasInstAwareBpps) {
    for (BeanPostProcessor bp : getBeanPostProcessors()) {
     if (bp instanceof InstantiationAwareBeanPostProcessor) {
      InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
      pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
      if (pvs == null) {
       return;
      }
     }
    }
   }
   if (needsDepCheck) {
    checkDependencies(beanName, mbd, filteredPds, pvs);
   }
  }

  if (pvs != null) {
      // 对属性进行注入
   applyPropertyValues(beanName, mbd, bw, pvs);
  }
 }

applyPropertyValues

/**
  * Apply the given property values, resolving any runtime references
  * to other beans in this bean factory. Must use deep copy, so we
  * don't permanently modify this property.
  * @param beanName the bean name passed for better exception information
  * @param mbd the merged bean definition
  * @param bw the BeanWrapper wrapping the target object
  * @param pvs the new property values
  */
 protected void applyPropertyValues(String beanName, BeanDefinition mbd, BeanWrapper bw, PropertyValues pvs) {
  if (pvs.isEmpty()) {
   return;
  }

  if (System.getSecurityManager() != null && bw instanceof BeanWrapperImpl) {
   ((BeanWrapperImpl) bw).setSecurityContext(getAccessControlContext());
  }

  MutablePropertyValues mpvs = null;
  List<PropertyValue> original;

  if (pvs instanceof MutablePropertyValues) {
   mpvs = (MutablePropertyValues) pvs;
   if (mpvs.isConverted()) {
    // Shortcut: use the pre-converted values as-is.
    try {
     bw.setPropertyValues(mpvs);
     return;
    }
    catch (BeansException ex) {
     throw new BeanCreationException(
       mbd.getResourceDescription(), beanName, "Error setting property values", ex);
    }
   }
   original = mpvs.getPropertyValueList();
  }
  else {
   original = Arrays.asList(pvs.getPropertyValues());
  }

  TypeConverter converter = getCustomTypeConverter();
  if (converter == null) {
   converter = bw;
  }
  BeanDefinitionValueResolver valueResolver = new BeanDefinitionValueResolver(this, beanName, mbd, converter);

  // Create a deep copy, resolving any references for values.
  List<PropertyValue> deepCopy = new ArrayList<>(original.size());
  boolean resolveNecessary = false;
  for (PropertyValue pv : original) {
   if (pv.isConverted()) {
    deepCopy.add(pv);
   }
   else {
    String propertyName = pv.getName();
    Object originalValue = pv.getValue();
    Object resolvedValue = valueResolver.resolveValueIfNecessary(pv, originalValue);
    Object convertedValue = resolvedValue;
    boolean convertible = bw.isWritableProperty(propertyName) &&
      !PropertyAccessorUtils.isNestedOrIndexedProperty(propertyName);
    if (convertible) {
     convertedValue = convertForProperty(resolvedValue, propertyName, bw, converter);
    }
    // Possibly store converted value in merged bean definition,
    // in order to avoid re-conversion for every created bean instance.
    if (resolvedValue == originalValue) {
     if (convertible) {
      pv.setConvertedValue(convertedValue);
     }
     deepCopy.add(pv);
    }
    else if (convertible && originalValue instanceof TypedStringValue &&
      !((TypedStringValue) originalValue).isDynamic() &&
      !(convertedValue instanceof Collection || ObjectUtils.isArray(convertedValue))) {
     pv.setConvertedValue(convertedValue);
     deepCopy.add(pv);
    }
    else {
     resolveNecessary = true;
     deepCopy.add(new PropertyValue(pv, convertedValue));
    }
   }
  }
  if (mpvs != null && !resolveNecessary) {
   mpvs.setConverted();
  }

  // Set our (possibly massaged) deep copy.
  try {
      // 依赖注入发生的地方,在BeanWrapperImpl中实现
   bw.setPropertyValues(new MutablePropertyValues(deepCopy));
  }
  catch (BeansException ex) {
   throw new BeanCreationException(
     mbd.getResourceDescription(), beanName, "Error setting property values", ex);
  }
 }

BeanWrapperImpl:setPropertyValues()

@Override
 public void setPropertyValue(PropertyValue pv) throws BeansException {
  PropertyTokenHolder tokens = (PropertyTokenHolder) pv.resolvedTokens;
  if (tokens == null) {
   String propertyName = pv.getName();
   AbstractNestablePropertyAccessor nestedPa;
   try {
    nestedPa = getPropertyAccessorForPropertyPath(propertyName);
   }
   catch (NotReadablePropertyException ex) {
    throw new NotWritablePropertyException(getRootClass(), this.nestedPath + propertyName,
      "Nested property in path '" + propertyName + "' does not exist", ex);
   }
   tokens = getPropertyNameTokens(getFinalPath(nestedPa, propertyName));
   if (nestedPa == this) {
    pv.getOriginalPropertyValue().resolvedTokens = tokens;
   }
   nestedPa.setPropertyValue(tokens, pv);
  }
  else {
   setPropertyValue(tokens, pv);
  }
 }

在BeanWrapperImpl的setPropertyValues()方法执行完之后,Bean的依赖注入也就完成了,可以供上层应用使用了。

4.2 lazyinit=false的情况

现在来看看lazyinit=false即预实例化的情况。
通过之前的分析已经知道ioc容器初始化的入口方法为refresh,而在refresh调用的一系列方法中有这样一个方法:
AbstractApplicationContext:finishBeanFactoryInitialization(beanFactory)

protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
  // Initialize conversion service for this context.
  if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&
    beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
   beanFactory.setConversionService(
     beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));
  }

  // Register a default embedded value resolver if no bean post-processor
  // (such as a PropertyPlaceholderConfigurer bean) registered any before:
  // at this point, primarily for resolution in annotation attribute values.
  if (!beanFactory.hasEmbeddedValueResolver()) {
   beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
  }

  // Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.
  String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
  for (String weaverAwareName : weaverAwareNames) {
   getBean(weaverAwareName);
  }

  // Stop using the temporary ClassLoader for type matching.
  beanFactory.setTempClassLoader(null);

  // Allow for caching all bean definition metadata, not expecting further changes.
  beanFactory.freezeConfiguration();

  // Instantiate all remaining (non-lazy-init) singletons.
  beanFactory.preInstantiateSingletons();
 }

看,源码的作者已经在beanFactory.preInstantiateSingletons()这个方法很贴心的为我们加上了 Instantiate all remaining (non-lazy-init) singletons.的注释,看来预实例化就是在这个方法中完成的了
DefaultListaleBeanFactory:preInstantiateSingletons()

 @Override
 public void preInstantiateSingletons() throws BeansException {
  if (logger.isDebugEnabled()) {
   logger.debug("Pre-instantiating singletons in " + this);
  }

  // Iterate over a copy to allow for init methods which in turn register new bean definitions.
  // While this may not be part of the regular factory bootstrap, it does otherwise work fine.
  List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);

  // Trigger initialization of all non-lazy singleton beans...
  for (String beanName : beanNames) {
   RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
   if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
    if (isFactoryBean(beanName)) {
     Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
     if (bean instanceof FactoryBean) {
      final FactoryBean<?> factory = (FactoryBean<?>) bean;
      boolean isEagerInit;
      if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
       isEagerInit = AccessController.doPrivileged((PrivilegedAction<Boolean>)
           ((SmartFactoryBean<?>) factory)::isEagerInit,
         getAccessControlContext());
      }
      else {
       isEagerInit = (factory instanceof SmartFactoryBean &&
         ((SmartFactoryBean<?>) factory).isEagerInit());
      }
      if (isEagerInit) {
       getBean(beanName);
      }
     }
    }
    else {
     getBean(beanName);
    }
   }
  }

  // Trigger post-initialization callback for all applicable beans...
  for (String beanName : beanNames) {
   Object singletonInstance = getSingleton(beanName);
   if (singletonInstance instanceof SmartInitializingSingleton) {
    final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
    if (System.getSecurityManager() != null) {
     AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
      smartSingleton.afterSingletonsInstantiated();
      return null;
     }, getAccessControlContext());
    }
    else {
     smartSingleton.afterSingletonsInstantiated();
    }
   }
  }
 }

可以看到依赖注入的实现还是通过(提前)调用getBean方法实现的(毕竟那么长一串代码当然要拿来复用啊orz)。而是否要预实例化的信息也没有什么意外,是保存在对应的BeanDefinition中的。

4.3 总结

那么两种依赖注入的情况到这就分析完毕了。预实例化虽然可以加快在容器启动后获取bean实例的速度,但是会拖慢容器的启动速度。一般情况下还是推荐使用lazy-init的(毕竟谁也不想一个项目启动半天吗orz)


5、容器其它相关特性的设计与实现

5.1 IOC容器的初始化与销毁动作

对于ioc容器,尤其是ApplicationContext,容器自身也有一个初始化与销毁的过程,这个过程可以简要的通过下图来表示
在这里插入图片描述
prepareBeanFactory在容器初始化的入口refresh方法中被调用
AbstractApplicationContext:prepareBeanFactory

 /**
  * Configure the factory's standard context characteristics,
  * such as the context's ClassLoader and post-processors.
  * @param beanFactory the BeanFactory to configure
  */
 protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
  // Tell the internal bean factory to use the context's class loader etc.
  beanFactory.setBeanClassLoader(getClassLoader());
  beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
  beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));

  // Configure the bean factory with context callbacks.
  beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
  beanFactory.ignoreDependencyInterface(EnvironmentAware.class);
  beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class);
  beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
  beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
  beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
  beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);

  // BeanFactory interface not registered as resolvable type in a plain factory.
  // MessageSource registered (and found for autowiring) as a bean.
  beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
  beanFactory.registerResolvableDependency(ResourceLoader.class, this);
  beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
  beanFactory.registerResolvableDependency(ApplicationContext.class, this);

  // Register early post-processor for detecting inner beans as ApplicationListeners.
  beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));

  // Detect a LoadTimeWeaver and prepare for weaving, if found.
  if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
   beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
   // Set a temporary ClassLoader for type matching.
   beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
  }

  // Register default environment beans.
  if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) {
   beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment());
  }
  if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) {
   beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties());
  }
  if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) {
   beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment());
  }
 }

而closeBeanFactory在关闭容器的方法close() -> doClose()中被调用

 @Override
 protected final void closeBeanFactory() {
  synchronized (this.beanFactoryMonitor) {
   if (this.beanFactory != null) {
    this.beanFactory.setSerializationId(null);
    this.beanFactory = null;
   }
  }
 }

5.2 Bean的初始化与销毁动作

在应用开发中常常要执行一些特定的初始化工作,如数据库连接,网络连接等,同时在结束服务时也有一些固定需要销毁的任务执行,因此spring ioc容器提供了相关功能可以让应用定制容器中的Bean的初始化与销毁过程。
为了实现这个需求,ioc容器提供了Bean什么周期各个时间点的回调接口供用户实现,这些实现将在initalizeBean方法中被调用。
首先介绍一下Bean的什么周期:

  1. Bean实例的创建
  2. 为Bean实例设置属性
  3. 调用Bean的初始化方法
  4. 应用可以通过ioc容器获取bean
  5. 当容器关闭时调用Bean的销毁方法

接下来看看在initalizeBean方法中的回调

protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {
  if (System.getSecurityManager() != null) {
   AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
    invokeAwareMethods(beanName, bean);
    return null;
   }, getAccessControlContext());
  }
  else {
   invokeAwareMethods(beanName, bean);
  }

  Object wrappedBean = bean;
  if (mbd == null || !mbd.isSynthetic()) {
   wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
  }

  try {
   invokeInitMethods(beanName, wrappedBean, mbd);
  }
  catch (Throwable ex) {
   throw new BeanCreationException(
     (mbd != null ? mbd.getResourceDescription() : null),
     beanName, "Invocation of init method failed", ex);
  }
  if (mbd == null || !mbd.isSynthetic()) {
   wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
  }

  return wrappedBean;
 }

   private void invokeAwareMethods(final String beanName, final Object bean) {
  if (bean instanceof Aware) {
   if (bean instanceof BeanNameAware) {
    ((BeanNameAware) bean).setBeanName(beanName);
   }
   if (bean instanceof BeanClassLoaderAware) {
    ClassLoader bcl = getBeanClassLoader();
    if (bcl != null) {
     ((BeanClassLoaderAware) bean).setBeanClassLoader(bcl);
    }
   }
   if (bean instanceof BeanFactoryAware) {
    ((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this);
   }
  }
 }

invokeInitmethods

 protected void invokeInitMethods(String beanName, final Object bean, @Nullable RootBeanDefinition mbd)
   throws Throwable {

  boolean isInitializingBean = (bean instanceof InitializingBean);
  if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {
   if (logger.isDebugEnabled()) {
    logger.debug("Invoking afterPropertiesSet() on bean with name '" + beanName + "'");
   }
   if (System.getSecurityManager() != null) {
    try {
     AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () -> {
      ((InitializingBean) bean).afterPropertiesSet();
      return null;
     }, getAccessControlContext());
    }
    catch (PrivilegedActionException pae) {
     throw pae.getException();
    }
   }
   else {
       // 调用afterPropertiesSet方法,方然前提是要实现IntializingBean接口
    ((InitializingBean) bean).afterPropertiesSet();
   }
  }

  if (mbd != null && bean.getClass() != NullBean.class) {
   String initMethodName = mbd.getInitMethodName();
   if (StringUtils.hasLength(initMethodName) &&
     !(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
     !mbd.isExternallyManagedInitMethod(initMethodName)) {
       // 判断是否配置了init-method
    invokeCustomInitMethod(beanName, bean, mbd);
   }
  }
 }

同样的,在容器关闭时可以在doClose方法中看到对bean销毁方法的调用(最终调用的是DisposabelAdapter的destroy方法)
DiposabelAdapter:destroy()

 @Override
 public void destroy() {
  if (!CollectionUtils.isEmpty(this.beanPostProcessors)) {
   for (DestructionAwareBeanPostProcessor processor : this.beanPostProcessors) {
    processor.postProcessBeforeDestruction(this.bean, this.beanName);
   }
  }

  if (this.invokeDisposableBean) {
   if (logger.isDebugEnabled()) {
    logger.debug("Invoking destroy() on bean with name '" + this.beanName + "'");
   }
   try {
    if (System.getSecurityManager() != null) {
     AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () -> {
      ((DisposableBean) this.bean).destroy();
      return null;
     }, this.acc);
    }
    else {
     ((DisposableBean) this.bean).destroy();
    }
   }
   catch (Throwable ex) {
    String msg = "Invocation of destroy method failed on bean with name '" + this.beanName + "'";
    if (logger.isDebugEnabled()) {
     logger.warn(msg, ex);
    }
    else {
     logger.warn(msg + ": " + ex);
    }
   }
  }

  if (this.destroyMethod != null) {
   invokeCustomDestroyMethod(this.destroyMethod);
  }
  else if (this.destroyMethodName != null) {
   Method methodToCall = determineDestroyMethod(this.destroyMethodName);
   if (methodToCall != null) {
    invokeCustomDestroyMethod(methodToCall);
   }
  }
 }

其中invokeCustomDestroyMethod方法就是对我们指定的Bean销毁方法的调用

5.3 FactoryBean的设计与实现

FactoryBean是一类特殊的Bean,这些FactoryBean生成需要特殊处理的对象,FactoryBean的生产特性是在getBean这个方法中体现的。
看看getObjectForBeanInstance这个方法的调用

protected Object getObjectForBeanInstance(
   Object beanInstance, String name, String beanName, @Nullable RootBeanDefinition mbd) {

  // Don't let calling code try to dereference the factory if the bean isn't a factory.
  if (BeanFactoryUtils.isFactoryDereference(name)) {
   if (beanInstance instanceof NullBean) {
    return beanInstance;
   }
   if (!(beanInstance instanceof FactoryBean)) {
    throw new BeanIsNotAFactoryException(transformedBeanName(name), beanInstance.getClass());
   }
  }

  // Now we have the bean instance, which may be a normal bean or a FactoryBean.
  // If it's a FactoryBean, we use it to create a bean instance, unless the
  // caller actually wants a reference to the factory.
  if (!(beanInstance instanceof FactoryBean) || BeanFactoryUtils.isFactoryDereference(name)) {
   return beanInstance;
  }

  Object object = null;
  if (mbd == null) {
   object = getCachedObjectForFactoryBean(beanName);
  }
  if (object == null) {
   // Return bean instance from factory.
   FactoryBean<?> factory = (FactoryBean<?>) beanInstance;
   // Caches object obtained from FactoryBean if it is a singleton.
   if (mbd == null && containsBeanDefinition(beanName)) {
    mbd = getMergedLocalBeanDefinition(beanName);
   }
   boolean synthetic = (mbd != null && mbd.isSynthetic());
   object = getObjectFromFactoryBean(factory, beanName, !synthetic);
  }
  return object;
 }

getObjectFromFactoryBean

protected Object getObjectFromFactoryBean(FactoryBean<?> factory, String beanName, boolean shouldPostProcess) {
  if (factory.isSingleton() && containsSingleton(beanName)) {
   synchronized (getSingletonMutex()) {
       //先尝试从缓存中获取
    Object object = this.factoryBeanObjectCache.get(beanName);
    if (object == null) {
     object = doGetObjectFromFactoryBean(factory, beanName);
     // Only post-process and store if not put there already during getObject() call above
     // (e.g. because of circular reference processing triggered by custom getBean calls)
     Object alreadyThere = this.factoryBeanObjectCache.get(beanName);
     if (alreadyThere != null) {
      object = alreadyThere;
     }
     else {
      if (shouldPostProcess) {
       if (isSingletonCurrentlyInCreation(beanName)) {
        // Temporarily return non-post-processed object, not storing it yet..
        return object;
       }
       beforeSingletonCreation(beanName);
       try {
        object = postProcessObjectFromFactoryBean(object, beanName);
       }
       catch (Throwable ex) {
        throw new BeanCreationException(beanName,
          "Post-processing of FactoryBean's singleton object failed", ex);
       }
       finally {
        afterSingletonCreation(beanName);
       }
      }
      if (containsSingleton(beanName)) {
       this.factoryBeanObjectCache.put(beanName, object);
      }
     }
    }
    return object;
   }
  }
  else {
   Object object = doGetObjectFromFactoryBean(factory, beanName);
   if (shouldPostProcess) {
    try {
     object = postProcessObjectFromFactoryBean(object, beanName);
    }
    catch (Throwable ex) {
     throw new BeanCreationException(beanName, "Post-processing of FactoryBean's object failed", ex);
    }
   }
   return object;
  }
 }

doGetObjectFromFactoryBean

 private Object doGetObjectFromFactoryBean(final FactoryBean<?> factory, final String beanName)
   throws BeanCreationException {

  Object object;
  try {
   if (System.getSecurityManager() != null) {
    AccessControlContext acc = getAccessControlContext();
    try {
     object = AccessController.doPrivileged((PrivilegedExceptionAction<Object>) factory::getObject, acc);
    }
    catch (PrivilegedActionException pae) {
     throw pae.getException();
    }
   }
   else {
    object = factory.getObject();
   }
  }
  catch (FactoryBeanNotInitializedException ex) {
   throw new BeanCurrentlyInCreationException(beanName, ex.toString());
  }
  catch (Throwable ex) {
   throw new BeanCreationException(beanName, "FactoryBean threw exception on object creation", ex);
  }

  // Do not accept a null value for a FactoryBean that's not fully
  // initialized yet: Many FactoryBeans just return null then.
  if (object == null) {
   if (isSingletonCurrentlyInCreation(beanName)) {
    throw new BeanCurrentlyInCreationException(
      beanName, "FactoryBean which is currently in creation returned null from getObject");
   }
   object = new NullBean();
  }
  return object;
 }

忽略复杂的处理过程,最后返回的bean对象依然是通过factory.getObject();
FactoryBean为我们提供了一个很好的封装机制,比如封装Proxy,RMI,JNDI等。

5.4 后置处理器BeanPostProcessor的设计与实现

BeanPostProcessor是使用ioc容器经常会遇到的特性,本质是一个后置处理的监听器,可以监听容器触发的各种事件。BeanPostProcessor的使用十分简单,只需要将实现了BeanPostProcessor的bean通过xml文件注入到容器中即可。
BeanPostProcessor是一个借口,有以下两个方法
在这里插入图片描述
其中postProcessorBeforeInitialization在Bean初始化之前调用,而postProcessorAfterInitialization在Bean初始化之后调用。而这个接口是在BeanFactory的initializeBean这个方法中与与ioc容器结合在一起的。
AbstractAutowireCapableBeanFactory:initializeBean

 protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {
  if (System.getSecurityManager() != null) {
   AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
    invokeAwareMethods(beanName, bean);
    return null;
   }, getAccessControlContext());
  }
  else {
   invokeAwareMethods(beanName, bean);
  }

  Object wrappedBean = bean;
  if (mbd == null || !mbd.isSynthetic()) {
   wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
  }

  try {
   invokeInitMethods(beanName, wrappedBean, mbd);
  }
  catch (Throwable ex) {
   throw new BeanCreationException(
     (mbd != null ? mbd.getResourceDescription() : null),
     beanName, "Invocation of init method failed", ex);
  }
  if (mbd == null || !mbd.isSynthetic()) {
   wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
  }

  return wrappedBean;
 }

注意在initializeBean中调用的applyBeanPostProcessorsBeforeInitializationapplyBeanPostProcessorsAfterInitialization这两个方法。(由此也可以看出此时回调获得的Bean已经完成了依赖注入的过程,而如果使用的是BeanFactoryPostProcessor则不然)
AbstractAutowireCapableBeanFactory:applyBeanPostProcessorsBeforeInitialization

 @Override
 public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
   throws BeansException {

  Object result = existingBean;
  for (BeanPostProcessor processor : getBeanPostProcessors()) {
   Object current = processor.postProcessBeforeInitialization(result, beanName);
   if (current == null) {
    return result;
   }
   result = current;
  }
  return result;
 }

   /**
  * Return the list of BeanPostProcessors that will get applied
  * to beans created with this factory.
  */
 public List<BeanPostProcessor> getBeanPostProcessors() {
  return this.beanPostProcessors;
 }

可以看到在applyBeanPostProcessorsBeforeInitialization中调用了所有注册到容器中的BeanPostProcessor的postProcessBeforeInitialization方法。applyBeanPostProcessorsAfterInitialization的实现与之相同。

5.5 Autowiring自动装配的设计与实现

自动装配的实现在分析依赖注入的populate()方法时已经说明过了,会分别根据自动注入的类型调用autowireByNameautowireByType方法,这里不再赘述。有感兴趣的读者可以自己阅读相关源码。
AbstractAutowiredCapableBeanFactory:autowiredByName

 protected void autowireByName(
   String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {

  String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
  for (String propertyName : propertyNames) {
   if (containsBean(propertyName)) {
    Object bean = getBean(propertyName);
    pvs.add(propertyName, bean);
    registerDependentBean(propertyName, beanName);
    if (logger.isDebugEnabled()) {
     logger.debug("Added autowiring by name from bean name '" + beanName +
       "' via property '" + propertyName + "' to bean named '" + propertyName + "'");
    }
   }
   else {
    if (logger.isTraceEnabled()) {
     logger.trace("Not autowiring property '" + propertyName + "' of bean '" + beanName +
       "' by name: no matching bean found");
    }
   }
  }
 }

AbstractAutowiredCapableBeanFactory:autowiredByType

 protected void autowireByType(
   String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {

  TypeConverter converter = getCustomTypeConverter();
  if (converter == null) {
   converter = bw;
  }

  Set<String> autowiredBeanNames = new LinkedHashSet<>(4);
  String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
  for (String propertyName : propertyNames) {
   try {
    PropertyDescriptor pd = bw.getPropertyDescriptor(propertyName);
    // Don't try autowiring by type for type Object: never makes sense,
    // even if it technically is a unsatisfied, non-simple property.
    if (Object.class != pd.getPropertyType()) {
     MethodParameter methodParam = BeanUtils.getWriteMethodParameter(pd);
     // Do not allow eager init for type matching in case of a prioritized post-processor.
     boolean eager = !PriorityOrdered.class.isInstance(bw.getWrappedInstance());
     DependencyDescriptor desc = new AutowireByTypeDependencyDescriptor(methodParam, eager);
     Object autowiredArgument = resolveDependency(desc, beanName, autowiredBeanNames, converter);
     if (autowiredArgument != null) {
      pvs.add(propertyName, autowiredArgument);
     }
     for (String autowiredBeanName : autowiredBeanNames) {
      registerDependentBean(autowiredBeanName, beanName);
      if (logger.isDebugEnabled()) {
       logger.debug("Autowiring by type from bean name '" + beanName + "' via property '" +
         propertyName + "' to bean named '" + autowiredBeanName + "'");
      }
     }
     autowiredBeanNames.clear();
    }
   }
   catch (BeansException ex) {
    throw new UnsatisfiedDependencyException(mbd.getResourceDescription(), beanName, propertyName, ex);
   }
  }
 }

附录

附录1 Spring ioc核心数据结构——BeanDefination

BeanDefination是Spring ioc的核心数据结构,通过对元数据的解析生成的包含一系列配置信息的数据结构。而这个数据结构中包含的信息将会影响包括实例的创建,依赖注入等各种Bean在容器内的行为,以下是BeanDefination接口的定义。
BeanDefinition<interface>
在这里插入图片描述


后记

使用了这么久spring总算认认真真读了一遍源码,感觉的确受益匪浅。接下来准备继续总结Aop,Spring MVC,数据库相关操作组件以及事务处理的相关源码。不定时更新(咕咕咕)。
第一次写这么长的博客,如果有什么错误或遗漏请联系博主指出。(鞠躬)

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:1136255
帖子:227251
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP