Spring源码解析(一):Spring的IOC实现

   概述

    在介绍Spring的IOC之前,我们先来介绍一下控制反转与依赖注入的概念,很多人觉得他们是一个意思,其实不然,控制反转是目的,而依赖注入是实现控制反转的方式。控制反转是一个面向对象的概念,它表示将类的内部的依赖关系交给其他机制去处理。而在Spring中的体现为,IOC容器就是Spring实现控制反转的载体,通过Spring的IOC容器实现的依赖反转,我们可以把依赖关系的管理从Java对象中解放出来,交给IOC容器来完成,从而完成了对象之间关系的解耦,原来的对象-对象的关系转化为了对象-IOC容器-对象的关系。

    在Spring的IOC容器的设计中,有两个主要的容器系列:一个是实现了BeanFactory的简单容器系列,一个是ApplicationContext应用上下文,它作为容器的高级形态存在。它们之间的继承关系如下:

     BeanFactory接口定义了容器的基本规范,在这个接口中包含了getBean()等IOC容器的基本方法。HierarchicalBeanFactory继承了BeanFactory之后添加了getParentBeanFactory()方法,使BeanFactory增加了双亲容器的管理功能,而在接下来的ConfigurableBeanFactory中又添加了一些对BeanFactory的配置功能,通过这些接口设计的叠加,定义了BeanFactory作为简单的IOC容器的基本功能。具体的BeanFactory容器例如DefaultListableBeanFactory、XMLBeanFactory都是这些接口的实现。

    而以ApplicationContext为核心的这一系列高级IOC容器,从BeanFactory到ListableBeanFactory和HierarchicalBeanFactory再到ApplicationContext,再到ConfigurableApplicationContext或者WebApplicationContext,我们常用的应用上下文基本上都是ConfigurableApplicationContext或者WebApplicationContext的实现。ApplicationContext在BeanFactory的基础上,通过继承MessageSource、ResourceLoader、ApplicationEventPublisher添加了许多对高级容器的特性的支持。

一、BeanFactory的实现

    BeanFactory接口提供了使用IOC容器的基本规范。BeanFactory接口代码如下:

public interface BeanFactory { 

String FACTORY_BEAN_PREFIX = "&";
Object getBean(String name) throws BeansException;
Object getBean(String name, Object... args) throws BeansException;
<T> T getBean(Class<T> requiredType) throws BeansException;
<T> T getBean(Class<T> requiredType, Object... args) throws BeansException;
boolean containsBean(String name);
boolean isSingleton(String name) throws NoSuchBeanDefinitionException;
boolean isPrototype(String name) throws NoSuchBeanDefinitionException;
boolean isTypeMatch(String name, ResolvableType typeToMatch) throws NoSuchBeanDefinitionException;
boolean isTypeMatch(String name, @Nullable Class<?> typeToMatch) throws NoSuchBeanDefinitionException;
@Nullable
Class<?> getType(String name) throws NoSuchBeanDefinitionException;
String[] getAliases(String name);

}

    以XmlBeanFactory为例我们来具体说明BeanFactory容器的设计原理,XmlBeanFactory类的继承关系如下:

   

    XmlBeanFactory继承自DefaultListableBeanFactory。DefaultListableBeanFactory是一个非常重要的类,是我们经常会看到的一个IOC实现,这个类包含了基本IOC容器的所有的重要功能。在其他IOC容器中,例如ApplicationContext,实现的基本原理与XmlBeanFactory类似,也是通过持有或者扩展DefaultListableBeanFactory来获取IOC容器的基本功能。XmlBeanFactory在它的功能的基础上,增加可以读取以XML文件定义的BeanDefinition的功能。在Spring中,BeanDefinition用来管理Spring应用中的各种对象以及它们之间的依赖关系,它抽象了我们对Bean的定义,是让容器起作用的主要数据类型。构造XmlBeanFactory容器时,需要先指定BeanDefinition的信息来源,这个信息来源需要封装成Spring中的Resource接口的实现,然后将Resource作为参数传给XmlBeanFactory的构造函数。这样,IOC容器就可以定位到需要的BeanDefinition信息来完成容器的初始化以及依赖注入。在XmlBeanFactory中,初始化了一个XmlBeanDefinitionReader对象,通过它来完成对XML信息的处理。在XmlBeanFactory的构造函数中使用这个对象来调用loadBeanDefinitions,就是这个调用启动了从Resource中载入BeanDefinition的过程。XmlBeanFactory代码如下:

public class XmlBeanFactory extends DefaultListableBeanFactory {
   private final XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(this);
   public XmlBeanFactory(Resource resource) throws BeansException {
      this(resource, null);
   }
   public XmlBeanFactory(Resource resource, BeanFactory parentBeanFactory) throws BeansException {
      super(parentBeanFactory);
      //从Resource中载入BeanDefinition
      this.reader.loadBeanDefinitions(resource);
   }
}

二、ApplicationContext的实现

    ApplicationContext与BeanFactory相比功能更加丰富,以FileSystemXmlApplicationContext为例,我们来具体分析IOC容器的初始化以及依赖注入的过程。FileSystemXmlApplicationContext的继承体系及代码如下:

public class FileSystemXmlApplicationContext extends AbstractXmlApplicationContext {
    public FileSystemXmlApplicationContext() {
    }
    public FileSystemXmlApplicationContext(ApplicationContext parent) {
        super(parent);
    }
    //configLocation包含的是包含BeanDefinition的文件路径
    public FileSystemXmlApplicationContext(String configLocation) throws BeansException {
        this(new String[]{configLocation}, true, (ApplicationContext)null);
    }
    //这个构造函数允许包含多个BeanDefinition的文件路径
    public FileSystemXmlApplicationContext(String... configLocations) throws BeansException {
        this(configLocations, true, (ApplicationContext)null);
    }
    //这个构造函数在上面的基础上还可以指定双亲容器
    public FileSystemXmlApplicationContext(String[] configLocations, ApplicationContext parent) throws BeansException {
        this(configLocations, true, parent);
    }
    public FileSystemXmlApplicationContext(String[] configLocations, boolean refresh) throws BeansException {
        this(configLocations, refresh, (ApplicationContext)null);
    }
    
    public FileSystemXmlApplicationContext(String[] configLocations, boolean refresh, ApplicationContext parent) throws BeansException {
        super(parent);
        this.setConfigLocations(configLocations);
        if (refresh) {
            //这个方法启动了对BeanDefinition的载入
            this.refresh();
        }
    }
    //这个方法用来定位Resource,它将在DefaultResouceLoader的getResource方法中被调用    
    protected Resource getResourceByPath(String path) {
        if (path != null && path.startsWith("/")) {
            path = path.substring(1);
        }
        return new FileSystemResource(path);
    }
}

2.1 容器的初始化

    容器的初始化通过在构造器中调用基类AbstractApplicationContext的refresh()方法启动,对于不同的容器,这个操作基本类似,它包括三个过程:

    第一个过程是Resource定位的过程, 这个过程是容器定位到数据所在的位置 。第二个过程是BeanDefinition的载入,容器通过这个过程把用户定义好的Bean转换成容器的内部数据结构——BeanDefinition,通过这个数据结构,容器能够方便对Bean进行管理。第三个过程是向IOC容器注册这些BeanDefinition的过程,这个过程把载入过程中解析到的BeanDefinition向IOC容器注册,容器通过一个HashMap来持有这些BeanDefinition。下面来具体分析这三个过程:

    1.Resource定位

    在前面我们使用BeanFactory时,需要先定义一个Resource来定位容器使用的BeanDefinition,然后通过BeanDefinitionReader来对这些信息进行处理,而在ApplicationContext中则不需要这些步骤,Spring已经为我们提供了一系列加载不同的Resource读取器的实现。

        对Resource的定位是从refresh()方法开始,下面我们来看看AbstractApplicationContext中的这个refresh()方法:

public void refresh() throws BeansException, IllegalStateException {
    Object var1 = this.startupShutdownMonitor;
    synchronized(this.startupShutdownMonitor) {
        this.prepareRefresh();
        //这里是开始Resource的定位的地方
        ConfigurableListableBeanFactory beanFactory = this.obtainFreshBeanFactory();
        this.prepareBeanFactory(beanFactory);

        try {
            //设置BeanFactory的后置处理
            this.postProcessBeanFactory(beanFactory);
            //调用BeanFactory的后置处理器
            this.invokeBeanFactoryPostProcessors(beanFactory);
            //注册Bean的后置处理,在Bean的创建过程中被调用
            this.registerBeanPostProcessors(beanFactory);
            //对上下文的消息源进行初始化
            this.initMessageSource();
            //初始化上下文中的事件机制
            this.initApplicationEventMulticaster();
            //初始化其他特殊的Bean
            this.onRefresh();
            //注册监听
            this.registerListeners();
            //实例化所有的(non-lazy-init)单件
            this.finishBeanFactoryInitialization(beanFactory);
            //发布容器事件,结束Refresh
            this.finishRefresh();
        } catch (BeansException var5) {
            this.logger.warn("Exception encountered during context initialization - cancelling refresh attempt", var5);
            this.destroyBeans();
            this.cancelRefresh(var5);
            throw var5;
        }

    }
}

obtainFreshBeanFactory()方法会调用AbstractRefreshableApplicationContext类中的refreshBeanFactory()方法,这个方法的具体代码如下:

protected final void refreshBeanFactory() throws BeansException {
    //如果已经建立了BeanFactory则销毁并关闭该BeanFactory    
    if (this.hasBeanFactory()) {
        this.destroyBeans();
        this.closeBeanFactory();
    }

    try {
        //创建一个DefaultListableBeanFactory实例
        DefaultListableBeanFactory beanFactory = this.createBeanFactory();
        beanFactory.setSerializationId(this.getId());
        this.customizeBeanFactory(beanFactory);
        //在这里使用BeanDefinitionReader载入Bean定义
        this.loadBeanDefinitions(beanFactory);
        Object var2 = this.beanFactoryMonitor;
        synchronized(this.beanFactoryMonitor) {
            this.beanFactory = beanFactory;
        }
    } catch (IOException var5) {
        throw new ApplicationContextException("I/O error parsing bean definition source for " + this.getDisplayName(), var5);
    }
}

loadBeanDefinitions是一个抽象方法,具体的实现在子类AbstractXmlApplicationContext中,代码如下:

protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
   
   XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);
   beanDefinitionReader.setEnvironment(this.getEnvironment());
   beanDefinitionReader.setResourceLoader(this);
   beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));
   initBeanDefinitionReader(beanDefinitionReader);
   loadBeanDefinitions(beanDefinitionReader);
}
//在这个方法中调用BeanDefinitionReader的loadBeanDefinitions来加载BeanDefinition
protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException {
   //getConfigResources默认返回null
   Resource[] configResources = getConfigResources();
   if (configResources != null) {
      reader.loadBeanDefinitions(configResources);
   }
   
   String[] configLocations = getConfigLocations();
   if (configLocations != null) {
      //FileSystemXmlApplicationContext构造器中会对configLocations进行初始化,所以会从这里进入
      reader.loadBeanDefinitions(configLocations);
   }
}

接着会调用XmlBeanDefinitionReader的父类AbstractBeanDefinitionReader中的loadBeanDefinition方法

public int loadBeanDefinitions(String location, @Nullable Set<Resource> actualResources) throws BeanDefinitionStoreException {
  //这里得到的DefaultResourceLoader, DefaultResourceLoader本来就是FileSystemXmlApplicationContext的父类
  ResourceLoader resourceLoader = getResourceLoader();
   if (resourceLoader == null) {
      throw new BeanDefinitionStoreException(
            "Cannot import bean definitions from location [" + location + "]: no ResourceLoader available");
   }

   if (resourceLoader instanceof ResourcePatternResolver) {
      try {
         //调用DefaultResourceLoader的getResource方法完成定位
         Resource[] resources = ((ResourcePatternResolver) resourceLoader).getResources(location);
         //载入和解析BeanDefinition
         int loadCount = loadBeanDefinitions(resources);
         if (actualResources != null) {
            for (Resource resource : resources) {
               actualResources.add(resource);
            }
         }
         if (logger.isDebugEnabled()) {
            logger.debug("Loaded " + loadCount + " bean definitions from location pattern [" + location + "]");
         }
         return loadCount;
      }
      catch (IOException ex) {
         throw new BeanDefinitionStoreException(
               "Could not resolve bean definition resource pattern [" + location + "]", ex);
      }
   }
   else {             
      //调用DefaultResourceLoader的getResource方法完成定位
      Resource resource = resourceLoader.getResource(location);
      //载入和解析BeanDefinition
      int loadCount = loadBeanDefinitions(resource);
      if (actualResources != null) {
         actualResources.add(resource);
      }
      if (logger.isDebugEnabled()) {
         logger.debug("Loaded " + loadCount + " bean definitions from location [" + location + "]");
      }
      return loadCount;
   }
}

再看看DefaultResourceLoader中是如何完成这个定位过程的

public Resource getResource(String location) {
   Assert.notNull(location, "Location must not be null");
   //处理带有classpath表示的Resource
   if (location.startsWith(CLASSPATH_URL_PREFIX)) {
      return new ClassPathResource(location.substring(CLASSPATH_URL_PREFIX.length()), getClassLoader());
   }
   else {
      try {
         //处理带有URL标识的Resource        
         URL url = new URL(location);
         return (ResourceUtils.isFileURL(url) ? new FileUrlResource(url) : new UrlResource(url));
      }
      catch (MalformedURLException ex) {
        //如果都不是则通过这个方法来处理,这个方法默认是得到一个ClassPathContextResource,在这里会调用
        //FileSystemXmlApplicationContext中重写的getResourceByPath方法
         return getResourceByPath(location);
      }
   }
}

至此,Resource的定位就完成了。

    2.BeanDefinition的载入和解析

    在上面的分析中我们看到,在初始化FileSystemXmlApplicationContext时通过调用refresh()方法来启动BeanDefinition的载入,具体的Resource的定位以及BeanDefinition载入是委托给XmlBeanDefinitionReader来完成的,对于不同形式的BeanDefinition,会用到不同的BeanDefinitionReader来进行载入。在完成Resource的定位后,接着会调用XmlBeanDefinitionReader中的loadBeanDefinition方法进行BeanDefinition的加载,具体实现加载的方法如下:

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

    doLoadBeanDefinitions代码如下

protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource) throws BeanDefinitionStoreException {
    try {
        //解析XML得到Document对象
        Document doc = this.doLoadDocument(inputSource, resource);
        //解析BeanDefinition
        return this.registerBeanDefinitions(doc, resource);
    } catch (BeanDefinitionStoreException var4) {
        throw var4;
    } catch (SAXParseException var5) {
        throw new XmlBeanDefinitionStoreException(resource.getDescription(), "Line " + var5.getLineNumber() + " in XML document from " + resource + " is invalid", var5);
    } catch (SAXException var6) {
        throw new XmlBeanDefinitionStoreException(resource.getDescription(), "XML document from " + resource + " is invalid", var6);
    } catch (ParserConfigurationException var7) {
        throw new BeanDefinitionStoreException(resource.getDescription(), "Parser configuration exception parsing XML from " + resource, var7);
    } catch (IOException var8) {
        throw new BeanDefinitionStoreException(resource.getDescription(), "IOException parsing XML document from " + resource, var8);
    } catch (Throwable var9) {
        throw new BeanDefinitionStoreException(resource.getDescription(), "Unexpected exception parsing XML document from " + resource, var9);
    }
}

    接着会在registerBeanDefinitions中使用BeanDefinitionDocumentReader来进行解析

public int registerBeanDefinitions(Document doc, Resource resource) throws BeanDefinitionStoreException {
    BeanDefinitionDocumentReader documentReader = this.createBeanDefinitionDocumentReader();
    documentReader.setEnvironment(this.getEnvironment());
    int countBefore = this.getRegistry().getBeanDefinitionCount();
    //具体的解析过程在这个方法中完成
    documentReader.registerBeanDefinitions(doc, this.createReaderContext(resource));
    return this.getRegistry().getBeanDefinitionCount() - countBefore;
}

    这里使用的BeanDefinitionDocumentReader是默认设置好的DefaultBeanDefinitionDocumentReader,解析的过程由BeanDefinitionParserDelegate完成,registerBeanDefinition方法代码如下:

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

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

    BeanDefinitionParserDelegate parent = this.delegate;
    this.delegate = this.createDelegate(this.readerContext, root, parent);
    //解析前的处理,由子类实现
    this.preProcessXml(root);
    //解析BeanDefinition
    this.parseBeanDefinitions(root, this.delegate);
    //解析后的处理,由子类实现
    this.postProcessXml(root);
    this.delegate = parent;
}
protected void parseBeanDefinitions(Element root, BeanDefinitionParserDelegate delegate) {
    //如果根节点使用的Spring默认命名空间
    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;
                //如果子节点使用的Spring默认命名空间,则用Spring默认的解析bean规则进行解析,否则使用
                  用户自定义的规则进行解析
                if (delegate.isDefaultNamespace(ele)) {
                    this.parseDefaultElement(ele, delegate);
                } else {
                    delegate.parseCustomElement(ele);
                }
            }
        }
    } else {
        //如果根节点没有使用默认的Spring的命名空间,则使用用户自定义的规则解析
        delegate.parseCustomElement(root);
    }

}
private void parseDefaultElement(Element ele, BeanDefinitionParserDelegate delegate) {
        //解析<Import>元素
        if (delegate.nodeNameEquals(ele, IMPORT_ELEMENT)) {
		importBeanDefinitionResource(ele);
	}
	//解析<Alias>别名元素
        else if (delegate.nodeNameEquals(ele, ALIAS_ELEMENT)) {
		processAliasRegistration(ele);
	}
	//解析一般的bean元素
        else if (delegate.nodeNameEquals(ele, BEAN_ELEMENT)) {
		processBeanDefinition(ele, delegate);
	}
	//如果元素为<beans>,则继续调用doRegisterBeanDefinitions进行解析
        else if (delegate.nodeNameEquals(ele, NESTED_BEANS_ELEMENT)) {
		// recurse
		doRegisterBeanDefinitions(ele);
	}
}

我们来看看对于一般的bean元素是如何进行解析的

protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) {
   //具体的解析是委托给BeanDefinitionParserDelegate来完成的,BeanDefinitionHolder中封装了BeanDefinition,Bean的名字和别名
   BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);
   if (bdHolder != null) {
      bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);
      try {
         // Register the final decorated instance.
        //向容器注册解析得到BeanDefinition 
        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));
   }
}

BeanDefinitionParserDelegate中如何对Bean进行处理

public BeanDefinitionHolder parseBeanDefinitionElement(Element ele, @Nullable BeanDefinition containingBean) {
		//获取id属性
                String id = ele.getAttribute(ID_ATTRIBUTE);
		//获取name属性
                String nameAttr = ele.getAttribute(NAME_ATTRIBUTE);
                //将name属性值存放到别名中
		List<String> aliases = new ArrayList<>();
		if (StringUtils.hasLength(nameAttr)) {
			String[] nameArr = StringUtils.tokenizeToStringArray(nameAttr, MULTI_VALUE_ATTRIBUTE_DELIMITERS);
			aliases.addAll(Arrays.asList(nameArr));
		}

		String beanName = id;
	        //如果Bean的id为空,那么将别名中的第一个值作为beanName
                if (!StringUtils.hasText(beanName) && !aliases.isEmpty()) {
			beanName = aliases.remove(0);
			if (logger.isDebugEnabled()) {
				logger.debug("No XML 'id' specified - using '" + beanName +
						"' as bean name and " + aliases + " as aliases");
			}
		}
                //检查id、name及别名是否重复,containingBean代表是否包含子bean元素
		if (containingBean == null) {
			checkNameUniqueness(beanName, aliases, ele);
		}
                //具体的对bean进行解析的地方
		AbstractBeanDefinition beanDefinition = parseBeanDefinitionElement(ele, beanName, containingBean);
		if (beanDefinition != null) {
			//如果id、name以及别名都为空
                        if (!StringUtils.hasText(beanName)) {
				try {
					//如果bean中不包含子<bean>元素那么为解析的bean生成一个beanName
                                        if (containingBean != null) {
						beanName = BeanDefinitionReaderUtils.generateBeanName(
								beanDefinition, this.readerContext.getRegistry(), true);
					}
					else {
						//如果包含子<bean>元素,那么生成一个beanName
                                                beanName = this.readerContext.generateBeanName(beanDefinition);
						// Register an alias for the plain bean class name, if still possible,
						// if the generator returned the class name plus a suffix.
						// This is expected for Spring 1.2/2.0 backwards compatibility.
						String beanClassName = beanDefinition.getBeanClassName();
						if (beanClassName != null &&
								beanName.startsWith(beanClassName) && beanName.length() > beanClassName.length() &&
								!this.readerContext.getRegistry().isBeanNameInUse(beanClassName)) {
							aliases.add(beanClassName);
						}
					}
					if (logger.isDebugEnabled()) {
						logger.debug("Neither XML 'id' nor 'name' specified - " +
								"using generated bean name [" + beanName + "]");
					}
				}
				catch (Exception ex) {
					error(ex.getMessage(), ele);
					return null;
				}
			}
			String[] aliasesArray = StringUtils.toStringArray(aliases);
			return new BeanDefinitionHolder(beanDefinition, beanName, aliasesArray);
		}

		return null;
	}

BeanDefinitionParserDelegate中对Bean的具体的属性的解析

public AbstractBeanDefinition parseBeanDefinitionElement(
			Element ele, String beanName, @Nullable BeanDefinition containingBean) {
                //记录解析了的bean
		this.parseState.push(new BeanEntry(beanName));
                //只读取<bean>中定义的class名字,然后载入到BeanDefinition中,只作个记录,具体对象的实例化是在依赖注入时完成
		String className = null;
                if (ele.hasAttribute(CLASS_ATTRIBUTE)) {
			className = ele.getAttribute(CLASS_ATTRIBUTE).trim();
		}
		String parent = null;
		//如果配置了parent属性,则获取parent属性值                
                if (ele.hasAttribute(PARENT_ATTRIBUTE)) {
			parent = ele.getAttribute(PARENT_ATTRIBUTE);
		}
		try {
			//生成BeanDefenition对象
                        AbstractBeanDefinition bd = createBeanDefinition(className, parent);
                        //对<bean>中配置的属性进行解析,如scope、lazy-init等
			parseBeanDefinitionAttributes(ele, beanName, containingBean, bd);
			//为BeanDefinition设置description信息
                        bd.setDescription(DomUtils.getChildElementValueByTagName(ele, DESCRIPTION_ELEMENT));
                        //以下是对<bean>的各种信息进行解析,meta、lookup-Method、replaced-Method
			parseMetaElements(ele, bd);
			parseLookupOverrideSubElements(ele, bd.getMethodOverrides());
			parseReplacedMethodSubElements(ele, bd.getMethodOverrides());
                        //解析构造函数设置
			parseConstructorArgElements(ele, bd);
			//解析property属性
                        parsePropertyElements(ele, bd);
			parseQualifierElements(ele, bd);

			bd.setResource(this.readerContext.getResource());
			bd.setSource(extractSource(ele));

			return bd;
		}
		catch (ClassNotFoundException ex) {
			error("Bean class [" + className + "] not found", ele, ex);
		}
		catch (NoClassDefFoundError err) {
			error("Class that bean class [" + className + "] depends on not found", ele, err);
		}
		catch (Throwable ex) {
			error("Unexpected failure during bean definition parsing", ele, ex);
		}
		finally {
			this.parseState.pop();
		}

		return null;
	}

对于我们用的最多的<property>属性,我们来看看是如何进行解析的

public void parsePropertyElements(Element beanEle, BeanDefinition bd) {
	//遍历所有子元素
        NodeList nl = beanEle.getChildNodes();
	for (int i = 0; i < nl.getLength(); i++) {
		Node node = nl.item(i);
		//如果为property元素则进行解析
              if (isCandidateElement(node) && nodeNameEquals(node, PROPERTY_ELEMENT)) {
                    parsePropertyElement((Element) node, bd);
              }
      }
}
        public void parsePropertyElement(Element ele, BeanDefinition bd) {
	        //取得property的名字
                String propertyName = ele.getAttribute(NAME_ATTRIBUTE);
		if (!StringUtils.hasLength(propertyName)) {
			error("Tag 'property' must have a 'name' attribute", ele);
			return;
		}
		this.parseState.push(new PropertyEntry(propertyName));
		try {
			//如果已经存在同名的property,那么不进行解析,直接返回。也就是说如果在bean中存在多个同名的property,那么
                        //只有第一个起作用
                        if (bd.getPropertyValues().contains(propertyName)) {
				error("Multiple 'property' definitions for property '" + propertyName + "'", ele);
				return;
			}
			//解析property值,并将解析的结果封装到PropertyValue中,然后设置到BeanDefinition中
                        Object val = parsePropertyValue(ele, bd, propertyName);
			PropertyValue pv = new PropertyValue(propertyName, val);
			parseMetaElements(ele, pv);
			pv.setSource(extractSource(ele));
			bd.getPropertyValues().addPropertyValue(pv);
		}
		finally {
			this.parseState.pop();
		}
	}
public Object parsePropertyValue(Element ele, BeanDefinition bd, @Nullable String propertyName) {
		String elementName = (propertyName != null) ?
						"<property> element for property '" + propertyName + "'" :
						"<constructor-arg> element";

		// property中只能有一个子元素,ref、value或者list等
		NodeList nl = ele.getChildNodes();
		Element subElement = null;
		for (int i = 0; i < nl.getLength(); i++) {
			Node node = nl.item(i);
			if (node instanceof Element && !nodeNameEquals(node, DESCRIPTION_ELEMENT) &&
					!nodeNameEquals(node, META_ELEMENT)) {
				if (subElement != null) {
					error(elementName + " must not contain more than one sub-element", ele);
				}
				else {
					subElement = (Element) node;
				}
			}
		}
                //判断property是ref还是value,不允许同时为ref和value
		boolean hasRefAttribute = ele.hasAttribute(REF_ATTRIBUTE);
		boolean hasValueAttribute = ele.hasAttribute(VALUE_ATTRIBUTE);
		if ((hasRefAttribute && hasValueAttribute) ||
				((hasRefAttribute || hasValueAttribute) && subElement != null)) {
			error(elementName +
					" is only allowed to contain either 'ref' attribute OR 'value' attribute OR sub-element", ele);
		}
                //如果为ref,则返回一个RuntimeBeanReference,这个对象封装了ref信息
                if (hasRefAttribute) {
			String refName = ele.getAttribute(REF_ATTRIBUTE);
			if (!StringUtils.hasText(refName)) {
				error(elementName + " contains empty 'ref' attribute", ele);
			}
			RuntimeBeanReference ref = new RuntimeBeanReference(refName);
			ref.setSource(extractSource(ele));
			return ref;
		}
		//如果为value,则返回一个TypedStringValue对象,这个对象封装了value信息
                else if (hasValueAttribute) {
			TypedStringValue valueHolder = new TypedStringValue(ele.getAttribute(VALUE_ATTRIBUTE));
			valueHolder.setSource(extractSource(ele));
			return valueHolder;
		}
		//如果还有子元素,则触发对子元素的解析
                else if (subElement != null) {
			return parsePropertySubElement(subElement, bd);
		}
		else {
			// Neither child element nor "ref" or "value" attribute found.
			error(elementName + " must specify a ref or value", ele);
			return null;
		}
	}

接下来是对<property>中子元素的解析,Array、List、Set、Map、Prop等元素都会在这里进行解析,生成对应的数据对象,生成对应的数据对象,比如ManagedList、ManagedArray、ManagedSet等。这些类是Spring对具体的BeanDefinition的封装。

public Object parsePropertySubElement(Element ele, BeanDefinition bd, String defaultValueType) {
		//如果子元素没有使用Spring默认的命名空间,那么使用用户自定义的规则解析元素                
                if (!isDefaultNamespace(ele)) {
			return parseNestedCustomElement(ele, bd);
		}
		//如果子元素为<bean>,那么继续进行解析                
                                    else if (nodeNameEquals(ele, BEAN_ELEMENT)) {
			BeanDefinitionHolder nestedBd = parseBeanDefinitionElement(ele, bd);
			if (nestedBd != null) {
				nestedBd = decorateBeanDefinitionIfRequired(ele, nestedBd, bd);
			}
			return nestedBd;
		}
		//如果子元素为ref,ref中包含的属性可以有local、bean、parent                
                else if (nodeNameEquals(ele, REF_ELEMENT)) {
			//获取ref中的bean属性值,bean属性可以引用不同配置文件中的bean的id
			String refName = ele.getAttribute(BEAN_REF_ATTRIBUTE);
			boolean toParent = false;                        
                        if (!StringUtils.hasLength(refName)) {
				//获取ref中的local属性,local属性可以引用同一xml中的bean的id
				refName = ele.getAttribute(LOCAL_REF_ATTRIBUTE);
				if (!StringUtils.hasLength(refName)) {
					//获取ref中的parent属性,parent属性可以引用父级容器中的bean
					refName = ele.getAttribute(PARENT_REF_ATTRIBUTE);
					toParent = true;
					//local、parent、bean都没有配置
                                        if (!StringUtils.hasLength(refName)) {
						error("'bean', 'local' or 'parent' is required for <ref> element", ele);
						return null;
					}
				}
			}
			//属性值为空                        
                        if (!StringUtils.hasText(refName)) {
				error("<ref> element contains empty target attribute", ele);
				return null;
			}
			//创建ref类型数据,指向被引用的对象
                        RuntimeBeanReference ref = new RuntimeBeanReference(refName, toParent);
			ref.setSource(extractSource(ele));
			return ref;
		}
		//解析<idref>子元素
                else if (nodeNameEquals(ele, IDREF_ELEMENT)) {
			return parseIdRefElement(ele);
		}
		//解析<value>子元素
                else if (nodeNameEquals(ele, VALUE_ELEMENT)) {
			return parseValueElement(ele, defaultValueType);
		}
		//如果子元素为null
                else if (nodeNameEquals(ele, NULL_ELEMENT)) {
			// It's a distinguished null value. Let's wrap it in a TypedStringValue
			// object in order to preserve the source location.
			TypedStringValue nullHolder = new TypedStringValue(null);
			nullHolder.setSource(extractSource(ele));
			return nullHolder;
		}
		//解析<array>子元素
                else if (nodeNameEquals(ele, ARRAY_ELEMENT)) {
			return parseArrayElement(ele, bd);
		}
		//解析<list>
                else if (nodeNameEquals(ele, LIST_ELEMENT)) {
			return parseListElement(ele, bd);
		}
		//解析<set>
                else if (nodeNameEquals(ele, SET_ELEMENT)) {
			return parseSetElement(ele, bd);
		}
		//解析<map>
                else if (nodeNameEquals(ele, MAP_ELEMENT)) {
			return parseMapElement(ele, bd);
		}
		//解析<props>
                else if (nodeNameEquals(ele, PROPS_ELEMENT)) {
			return parsePropsElement(ele);
		}
		else {
			error("Unknown property sub-element: [" + ele.getNodeName() + "]", ele);
			return null;
		}
	}

经过这样的逐层解析,我们在配置文件中定义的Bean就被转换成了容器中的数据结构--BeanDefinition,IOC容器通过它来对数据进行索引、查询和操作。经过这个载入的过程,容器大致完成了Bean对象的数据准备工作。接下来,就是数据向容器注册的过程。

2.2 容器的依赖注入

   依赖注入的过程可能有两种情况触发:如果bean为singleton并且未配置lazy-init属性(默认为false),那么会在初始化容器时,在解析载入BeanDefinition时会触发Bean的预实例化,这个过程会触发bean的依赖注入。否则就在用户第一次调用getBean向IOC容器索要bean时触发。第一种情况我们在下一篇中再来详细说明,首先来看看第二种情况,下面是DefaultListableBeanFactory的基类AbstractBeanFactory中getBean的实现

        public Object getBean(String name) throws BeansException {
		return doGetBean(name, null, null, false);
	}
	public <T> T getBean(String name, Class<T> requiredType) throws BeansException {
		return doGetBean(name, requiredType, null, false);
	}
         public Object getBean(String name, Object... args) throws BeansException {
		return doGetBean(name, null, args, false);
	}
	public <T> T getBean(String name, Class<T> requiredType, Object... args) throws BeansException {
		return doGetBean(name, requiredType, args, false);
	}

实际取得bean的地方在doGetBean方法中,这里也是实际发生依赖注入的地方

protected <T> T doGetBean(
			final String name, final Class<T> requiredType, 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的生产结果
                        bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
		}

		else {
			if (isPrototypeCurrentlyInCreation(beanName)) {
				throw new BeanCurrentlyInCreationException(beanName);
			}

			// 对容器中的BeanDefinition是否存在进行检查,检查是否能在当前的BeanFactory中取得需要的bean,如果取不到就一直沿着
                        // 父级BeanFactory链一直向上查找
                        BeanFactory parentBeanFactory = getParentBeanFactory();
                        //如果存在父级容器并且当前容器中不存在指定名称的Bean
                        if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
				String nameToLookup = originalBeanName(name);
				if (args != null) {
					// Delegation to parent with explicit args.
					return (T) parentBeanFactory.getBean(nameToLookup, args);
				}
				else {
					return parentBeanFactory.getBean(nameToLookup, requiredType);
				}
			}

			if (!typeCheckOnly) {
				markBeanAsCreated(beanName);
			}
                        
			try {
				//获取BeanDefinition
                                final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
				checkMergedBeanDefinition(mbd, beanName, args);

				// 获取的当前Bean的所有依赖Bean
				String[] dependsOn = mbd.getDependsOn();
				if (dependsOn != null) {
					//遍历所有的依赖Bean,递归调用getBean方法,直到取到一个没有任何依赖的Bean
                                        for (String dependsOnBean : dependsOn) {
						if (isDependent(beanName, dependsOnBean)) {
							throw new BeanCreationException(mbd.getResourceDescription(), beanName,
									"Circular depends-on relationship between '" + beanName + "' and '" + dependsOnBean + "'");
						}
						registerDependentBean(dependsOnBean, beanName);
						getBean(dependsOnBean);
					}
				}

				// 创建singleton模式的bean,在getSingleton方法中会调用这个匿名内部类的getObject方法
				if (mbd.isSingleton()) {
					sharedInstance = getSingleton(beanName, new ObjectFactory<Object>() {
						public Object getObject() throws BeansException {
							try {
								return createBean(beanName, mbd, args);
							}
							catch (BeansException ex) {
								destroySingleton(beanName);
								throw ex;
							}
						}
					});
					bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
				}
                                //创建prototype模式的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 {
                                        //如果既不是singleton模式也不是prototype模式则根据定义bean的资源文件中配置的作用域选择实例化
                                        //的方法,如request,session等
                                        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, new ObjectFactory<Object>() {
							public Object getObject() throws BeansException {
								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.
		if (requiredType != null && bean != null && !requiredType.isAssignableFrom(bean.getClass())) {
			try {
				return getTypeConverter().convertIfNecessary(bean, requiredType);
			}
			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;
	}

在这要说明一下的是doGetBean中调用的getObjectForBeanInstance方法,这个方法中进行了对FactoryBean的一些处理,FactoryBean与BeanFactory看起来非常相似,实际上完全不同,BeanFactory是IOC容器的抽象,而FactoryBean是一种特殊的Bean,它是一个可以产生或者修饰对象的工厂Bean,与设计模式中的工厂模式以及装饰器模式类似。通过实现org.springframework.beans.factory.FactoryBean来创建一个FactoryBean,我们调用它的getBean方法时,得到的是它的生成的对象,如果想得到Factory本身,需要在前面加上转义符“&”。

下面我们来看看doGetBean中调用的createBean方法,这个方法中包含了具体的bean的对象的创建过程,在AbstractAutowireCapableBeanFactory中实现了这个createBean,具体的代码如下

protected Object createBean(String beanName, RootBeanDefinition mbd, Object[] args) throws BeanCreationException {
		if (logger.isDebugEnabled()) {
			logger.debug("Creating instance of bean '" + beanName + "'");
		}
		RootBeanDefinition mbdToUse = mbd;
                //判断需要创建的bean是否可以实例化,这个类是否可以通过类装载器来载入
		Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
		if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
			mbdToUse = new RootBeanDefinition(mbd);
			mbdToUse.setBeanClass(resolvedClass);
		}

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

		try {
			//如果bean配置了PostProcessor,则返回一个proxy
                        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);
		}
                //这里是创建bean的方法
		Object beanInstance = doCreateBean(beanName, mbdToUse, args);
		if (logger.isDebugEnabled()) {
			logger.debug("Finished creating instance of bean '" + beanName + "'");
		}
		return beanInstance;
	}
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args) {
		// 这个BeanWrapper对象用来持有创建的Bean
		BeanWrapper instanceWrapper = null;
		//如果是singleton,则清除缓存中同名的bean
                if (mbd.isSingleton()) {
			instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
		}
		//这里是创建bean的地方
                if (instanceWrapper == null) {
			instanceWrapper = createBeanInstance(beanName, mbd, args);
		}
		final Object bean = (instanceWrapper != null ? instanceWrapper.getWrappedInstance() : null);
		Class<?> beanType = (instanceWrapper != null ? instanceWrapper.getWrappedClass() : null);
                //调用PostProcessor
		synchronized (mbd.postProcessingLock) {
			if (!mbd.postProcessed) {
				applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
				mbd.postProcessed = true;
			}
		}

		// 缓存singleton模式的bean以防循环引用
		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, new ObjectFactory<Object>() {
				@Override
				public Object getObject() throws BeansException {
					return getEarlyBeanReference(beanName, mbd, bean);
				}
			});
		}

		// 对Bean的初始化,也是依赖注入发生的地方,这个exposedObject在完成初始化处理之后会作为依赖注入完成后的bean返回
		Object exposedObject = bean;
		try {
			populateBean(beanName, mbd, instanceWrapper);
			if (exposedObject != null) {
				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) {
			//根据beanName获取已经注册过的singleton的bean对象
                        Object earlySingletonReference = getSingleton(beanName, false);
			if (earlySingletonReference != null) {
				//如果开始创建的bean与初始化处理之后的bean是同一个bean
                                if (exposedObject == bean) {
				    //那么返回获取的已经注册bean
                                    exposedObject = earlySingletonReference;
				}
				//当前bean依赖其他bean,并且存在循环引用时不允许创建新的对象
                                else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
					String[] dependentBeans = getDependentBeans(beanName);
					Set<String> actualDependentBeans = new LinkedHashSet<String>(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.");
					}
				}
			}
		}

		// 注册完成注入的bean
		try {
			registerDisposableBeanIfNecessary(beanName, bean, mbd);
		}
		catch (BeanDefinitionValidationException ex) {
			throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
		}

		return exposedObject;
	}

在doCreateBean中,具体的bean对象由createBeanInstance生成,这个对象的生成由很多种方式,可以通过工厂方法(factory-method)生成,也可以通过构造函数生成,而具体的依赖注入由populateBean触发。下面来看看这两个方法的代码

protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, Object[] args) {
		// 确认需要创建的Bean的类可以被实例化
		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());
		}
                //使用工厂方法进行实例化
		if (mbd.getFactoryMethodName() != null)  {
			return instantiateUsingFactoryMethod(beanName, mbd, args);
		}

		boolean resolved = false;
		boolean autowireNecessary = false;
		    if (args == null) {
			synchronized (mbd.constructorArgumentLock) {
				//一个类有多个构造函数则根据参数来确定使用哪一个构造函数
                                if (mbd.resolvedConstructorOrFactoryMethod != null) {
					resolved = true;
					autowireNecessary = mbd.constructorArgumentsResolved;
				}
			}
		}
		//如果是之前已经解析过的则不需要重复解析,直接取resolvedConstructorOrFactoryMethod,否则需要重新解析,并将解析的结果
                //缓存到resolvedConstructorOrFactoryMethod         
                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);
		}

		// 默认的构造器实例化
		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(new PrivilegedAction<Object>() {
					@Override
					public Object run() {
						return getInstantiationStrategy().instantiate(mbd, beanName, parent);
					}
				}, getAccessControlContext());
			}
			else {
                                 //实例化对象的方法,默认会调用SimpleInstantiationStrategy的instantiate方法
                                 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);
		}
	}
public Object instantiate(RootBeanDefinition bd, String beanName, BeanFactory owner) {
		// 如果没有需要动态改变的方法,直接用反射创建对象
		if (bd.getMethodOverrides().isEmpty()) {
			Constructor<?> constructorToUse;
			synchronized (bd.constructorArgumentLock) {
				constructorToUse = (Constructor<?>) bd.resolvedConstructorOrFactoryMethod;
				if (constructorToUse == null) {
					final Class<?> clazz = bd.getBeanClass();
					if (clazz.isInterface()) {
						throw new BeanInstantiationException(clazz, "Specified class is an interface");
					}
					try {
						if (System.getSecurityManager() != null) {
							constructorToUse = AccessController.doPrivileged(new PrivilegedExceptionAction<Constructor<?>>() {
								@Override
								public Constructor<?> run() throws Exception {
									return clazz.getDeclaredConstructor((Class[]) null);
								}
							});
						}
						else {
							constructorToUse =	clazz.getDeclaredConstructor((Class[]) null);
						}
						bd.resolvedConstructorOrFactoryMethod = constructorToUse;
					}
					catch (Throwable ex) {
						throw new BeanInstantiationException(clazz, "No default constructor found", ex);
					}
				}
			}
			return BeanUtils.instantiateClass(constructorToUse);
		}
		else {
			// 如果有方法覆盖或者动态替换的方法则需要cglib进行动态代理,例如配置了lookup-method
			return instantiateWithMethodInjection(bd, beanName, owner);
		}
	}
protected void populateBean(String beanName, RootBeanDefinition mbd, BeanWrapper bw) {
		//取得在BeanDefinition中设置的property值
                PropertyValues pvs = mbd.getPropertyValues();
		if (bw == null) {
			if (!pvs.isEmpty()) {
				throw new BeanCreationException(
						mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
			}
			else {
				return;
			}
		}
                //进行后处理器的调用
                boolean continueWithPropertyPopulation = true;
		if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
			for (BeanPostProcessor bp : getBeanPostProcessors()) {
				if (bp instanceof InstantiationAwareBeanPostProcessor) {
					InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
					//返回值为是否继续进行bean的填充
                                        if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
						continueWithPropertyPopulation = false;
						break;
					}
				}
			}
		}
                //如果后处理器中返回false,那么直接return
		if (!continueWithPropertyPopulation) {
			return;
		}
                //开始进行依赖注入,先处理autowire的注入,可以根据bean的名字或者类型来完成
		if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME ||
				mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
			MutablePropertyValues newPvs = new MutablePropertyValues(pvs);

			if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME) {
				autowireByName(beanName, mbd, bw, newPvs);
			}

			if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
				autowireByType(beanName, mbd, bw, newPvs);
			}

			pvs = newPvs;
		}
                
                //后处理器是否已经初始化
                boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
		//是否需要依赖检查
                boolean needsDepCheck = (mbd.getDependencyCheck() != RootBeanDefinition.DEPENDENCY_CHECK_NONE);

		if (hasInstAwareBpps || needsDepCheck) {
			//对需要进行依赖检查的属性进行后处理器处理
                        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);
			}
		}
                //对属性解析然后进行注入
		applyPropertyValues(beanName, mbd, bw, pvs);
	}

下面来看applyPropertyValues方法,对bean的属性解析并注入的过程在这个方法中进行

protected void applyPropertyValues(String beanName, BeanDefinition mbd, BeanWrapper bw, PropertyValues pvs) {
		if (pvs == null || pvs.isEmpty()) {
			return;
		}
                //封装PropertyValues
		MutablePropertyValues mpvs = null;
		List<PropertyValue> original;

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

		if (pvs instanceof MutablePropertyValues) {
			mpvs = (MutablePropertyValues) pvs;
			//如果mpvs中的值已经转换为对应的类型,那么可以直接设置到beanwrapper中
                        if (mpvs.isConverted()) {
				try {
					bw.setPropertyValues(mpvs);
					return;
				}
				catch (BeansException ex) {
					throw new BeanCreationException(
							mbd.getResourceDescription(), beanName, "Error setting property values", ex);
				}
			}
			original = mpvs.getPropertyValueList();
		}
		//如果pvs不是MutablePropertyValues封装的类型
                else {
			original = Arrays.asList(pvs.getPropertyValues());
		}
                //获取用户自定义的类型转换器
		TypeConverter converter = getCustomTypeConverter();
		if (converter == null) {
			converter = bw;
		}
		BeanDefinitionValueResolver valueResolver = new BeanDefinitionValueResolver(this, beanName, mbd, converter);

		// 为解析的值创建一个副本,副本的数据会被注入到bean中
		List<PropertyValue> deepCopy = new ArrayList<PropertyValue>(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);
				}
				//如果转换了的话就将转换的值缓存起来,免得每次注入的时候都要转换一次                    
				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));
				}
			}
		}
		//转换过了就将标记位置为true
                if (mpvs != null && !resolveNecessary) {
			mpvs.setConverted();
		}

		//开始进行依赖注入
		try {
			bw.setPropertyValues(new MutablePropertyValues(deepCopy));
		}
		catch (BeansException ex) {
			throw new BeanCreationException(
					mbd.getResourceDescription(), beanName, "Error setting property values", ex);
		}
	}

在这个方法中先通过BeanDefinitionResolver来对BeanDefinition进行解析,然后注入到property中。下面我们来看一下BeanDefinitionResolver中的解析过程的实现。

public Object resolveValueIfNecessary(Object argName, Object value) {
		//对引用类型的属性进行解析
                if (value instanceof RuntimeBeanReference) {
			RuntimeBeanReference ref = (RuntimeBeanReference) value;
			return resolveReference(argName, ref);
		}
		else if (value instanceof RuntimeBeanNameReference) {
			String refName = ((RuntimeBeanNameReference) value).getBeanName();
			refName = String.valueOf(doEvaluate(refName));
			if (!this.beanFactory.containsBean(refName)) {
				throw new BeanDefinitionStoreException(
						"Invalid bean name '" + refName + "' in bean reference for " + argName);
			}
			return refName;
		}
		//对类型为<bean>的属性的解析
                else if (value instanceof BeanDefinitionHolder) {
			BeanDefinitionHolder bdHolder = (BeanDefinitionHolder) value;
			return resolveInnerBean(argName, bdHolder.getBeanName(), bdHolder.getBeanDefinition());
		}
		else if (value instanceof BeanDefinition) {
			BeanDefinition bd = (BeanDefinition) value;
			String innerBeanName = "(inner bean)" + BeanFactoryUtils.GENERATED_BEAN_NAME_SEPARATOR +
					ObjectUtils.getIdentityHexString(bd);
			return resolveInnerBean(argName, innerBeanName, bd);
		}
		//对数组类型的bean的解析
                else if (value instanceof ManagedArray) {
			ManagedArray array = (ManagedArray) value;
			//获取数组的类型
                        Class<?> elementType = array.resolvedElementType;
			if (elementType == null) {
				//获取元素的类型名称
                                String elementTypeName = array.getElementTypeName();
				if (StringUtils.hasText(elementTypeName)) {
					try {
						//通过反射得到元素类型并记录
                                                elementType = ClassUtils.forName(elementTypeName, this.beanFactory.getBeanClassLoader());
						array.resolvedElementType = elementType;
					}
					catch (Throwable ex) {
						throw new BeanCreationException(
								this.beanDefinition.getResourceDescription(), this.beanName,
								"Error resolving array type for " + argName, ex);
					}
				}
				?/如果没有获取到数组类型也没有获取到元素类型那么直接设置类型为Object
                                else {
					elementType = Object.class;
				}
			}
			//解析数组
                        return resolveManagedArray(argName, (List<?>) value, elementType);
		}
		//解析list类型的属性
                else if (value instanceof ManagedList) {
			return resolveManagedList(argName, (List<?>) value);
		}
		//解析set类型的属性
                else if (value instanceof ManagedSet) {
			return resolveManagedSet(argName, (Set<?>) value);
		}
		//解析map类型的属性
                else if (value instanceof ManagedMap) {
			return resolveManagedMap(argName, (Map<?, ?>) value);
		}
		//解析props类型的属性
                else if (value instanceof ManagedProperties) {
			Properties original = (Properties) value;
			Properties copy = new Properties();
			for (Map.Entry<Object, Object> propEntry : original.entrySet()) {
				Object propKey = propEntry.getKey();
				Object propValue = propEntry.getValue();
				if (propKey instanceof TypedStringValue) {
					propKey = evaluate((TypedStringValue) propKey);
				}
				if (propValue instanceof TypedStringValue) {
					propValue = evaluate((TypedStringValue) propValue);
				}
				copy.put(propKey, propValue);
			}
			return copy;
		}
		//对字符串类型的属性进行解析
                else if (value instanceof TypedStringValue) {
			TypedStringValue typedStringValue = (TypedStringValue) value;
			Object valueObject = evaluate(typedStringValue);
			try {
				Class<?> resolvedTargetType = resolveTargetType(typedStringValue);
				if (resolvedTargetType != null) {
					return this.typeConverter.convertIfNecessary(valueObject, resolvedTargetType);
				}
				else {
					return valueObject;
				}
			}
			catch (Throwable ex) {
				throw new BeanCreationException(
						this.beanDefinition.getResourceDescription(), this.beanName,
						"Error converting typed String value for " + argName, ex);
			}
		}
		else {
			return evaluate(value);
		}
	}

对于我们使用较多的引用类型我们来看看是如何解析的

private Object resolveReference(Object argName, RuntimeBeanReference ref) {
		try {
			//取得引用的BeanName
                        String refName = ref.getBeanName();
			refName = String.valueOf(doEvaluate(refName));
			//如果引用的在父级容器中,就到父级容器中去取
                        if (ref.isToParent()) {
				if (this.beanFactory.getParentBeanFactory() == null) {
					throw new BeanCreationException(
							this.beanDefinition.getResourceDescription(), this.beanName,
							"Can't resolve reference to bean '" + refName +
							"' in parent factory: no parent factory available");
				}
				return this.beanFactory.getParentBeanFactory().getBean(refName);
			}
			//否则到当前容器中取,这里会触发一个getBean的过程
                        else {
				Object bean = this.beanFactory.getBean(refName);
				this.beanFactory.registerDependentBean(refName, this.beanName);
				return bean;
			}
		}
		catch (BeansException ex) {
			throw new BeanCreationException(
					this.beanDefinition.getResourceDescription(), this.beanName,
					"Cannot resolve reference to bean '" + ref.getBeanName() + "' while setting " + argName, ex);
		}
	}

对于数组集合类型的属性的解析基本类似,以list为例我们来看看是如何解析的

private List<?> resolveManagedList(Object argName, List<?> ml) {
		List<Object> resolved = new ArrayList<Object>(ml.size());
		//遍历集合,递归的解析每一个元素
                for (int i = 0; i < ml.size(); i++) {
			resolved.add(
					resolveValueIfNecessary(new KeyedArgName(argName, i), ml.get(i)));
		}
		return resolved;
	}

在完成这个解析过程后,已经为依赖注入准备好了条件。依赖注入是通过调用BeanWrapper的setPropertyValues方法启动的,这个方法的具体实现在AbstractNestablePropertyAccessor的setPropertyValue中,方法代码如下

protected void setPropertyValue(PropertyTokenHolder tokens, PropertyValue pv) throws BeansException {
		String propertyName = tokens.canonicalName;
		String actualName = tokens.actualName;
                //tokens存放的是属性的名称集合的size等信息 keys存放的是集合的size
		if (tokens.keys != null) {
			//拷贝tokens中的信息
                        PropertyTokenHolder getterTokens = new PropertyTokenHolder();
			getterTokens.canonicalName = tokens.canonicalName;
			getterTokens.actualName = tokens.actualName;
			getterTokens.keys = new String[tokens.keys.length - 1];
			System.arraycopy(tokens.keys, 0, getterTokens.keys, 0, tokens.keys.length - 1);
			Object propValue;
			try {
				//获取属性的值,该方法内部使用了jdk的内省机制
                                propValue = getPropertyValue(getterTokens);
			}
			catch (NotReadablePropertyException ex) {
				throw new NotWritablePropertyException(getRootClass(), this.nestedPath + propertyName,
						"Cannot access indexed value in property referenced " +
						"in indexed property path '" + propertyName + "'", ex);
			}
			//获取集合属性的长度
			String key = tokens.keys[tokens.keys.length - 1];
			if (propValue == null) {
				// null map value case
				if (isAutoGrowNestedPaths()) {
					// TODO: cleanup, this is pretty hacky
					int lastKeyIndex = tokens.canonicalName.lastIndexOf('[');
					getterTokens.canonicalName = tokens.canonicalName.substring(0, lastKeyIndex);
					propValue = setDefaultValue(getterTokens);
				}
				else {
					throw new NullValueInNestedPathException(getRootClass(), this.nestedPath + propertyName,
							"Cannot access indexed value in property referenced " +
							"in indexed property path '" + propertyName + "': returned null");
				}
			}
                        //注入Array类型的属性值 
                        if (propValue.getClass().isArray()) {
				PropertyHandler ph = getLocalPropertyHandler(actualName);
				Class<?> requiredType = propValue.getClass().getComponentType();
				int arrayIndex = Integer.parseInt(key);
				Object oldValue = null;
				try {
					if (isExtractOldValueForEditor() && arrayIndex < Array.getLength(propValue)) {
						oldValue = Array.get(propValue, arrayIndex);
					}
					Object convertedValue = convertIfNecessary(propertyName, oldValue, pv.getValue(),
							requiredType, ph.nested(tokens.keys.length));
					int length = Array.getLength(propValue);
					if (arrayIndex >= length && arrayIndex < this.autoGrowCollectionLimit) {
						Class<?> componentType = propValue.getClass().getComponentType();
						Object newArray = Array.newInstance(componentType, arrayIndex + 1);
						System.arraycopy(propValue, 0, newArray, 0, length);
						setPropertyValue(actualName, newArray);
						propValue = getPropertyValue(actualName);
					}
					Array.set(propValue, arrayIndex, convertedValue);
				}
				catch (IndexOutOfBoundsException ex) {
					throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
							"Invalid array index in property path '" + propertyName + "'", ex);
				}
			}
                        //注入list类型属性的值
			else if (propValue instanceof List) {
				PropertyHandler ph = getPropertyHandler(actualName);
				Class<?> requiredType = ph.getCollectionType(tokens.keys.length);
				List<Object> list = (List<Object>) propValue;
				int index = Integer.parseInt(key);
				Object oldValue = null;
				if (isExtractOldValueForEditor() && index < list.size()) {
					oldValue = list.get(index);
				}
				Object convertedValue = convertIfNecessary(propertyName, oldValue, pv.getValue(),
						requiredType, ph.nested(tokens.keys.length));
				int size = list.size();
				if (index >= size && index < this.autoGrowCollectionLimit) {
					for (int i = size; i < index; i++) {
						try {
							list.add(null);
						}
						catch (NullPointerException ex) {
							throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
									"Cannot set element with index " + index + " in List of size " +
									size + ", accessed using property path '" + propertyName +
									"': List does not support filling up gaps with null elements");
						}
					}
					list.add(convertedValue);
				}
				else {
					try {
						list.set(index, convertedValue);
					}
					catch (IndexOutOfBoundsException ex) {
						throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
								"Invalid list index in property path '" + propertyName + "'", ex);
					}
				}
			}
			//注入map类型属性的值
                        else if (propValue instanceof Map) {
				PropertyHandler ph = getLocalPropertyHandler(actualName);
				Class<?> mapKeyType = ph.getMapKeyType(tokens.keys.length);
				Class<?> mapValueType = ph.getMapValueType(tokens.keys.length);
				Map<Object, Object> map = (Map<Object, Object>) propValue;
				TypeDescriptor typeDescriptor = TypeDescriptor.valueOf(mapKeyType);
				Object convertedMapKey = convertIfNecessary(null, null, key, mapKeyType, typeDescriptor);
				Object oldValue = null;
				if (isExtractOldValueForEditor()) {
					oldValue = map.get(convertedMapKey);
				}
				Object convertedMapValue = convertIfNecessary(propertyName, oldValue, pv.getValue(),
						mapValueType, ph.nested(tokens.keys.length));
				map.put(convertedMapKey, convertedMapValue);
			}
			else {
				throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
						"Property referenced in indexed property path '" + propertyName +
						"' is neither an array nor a List nor a Map; returned value was [" + propValue + "]");
			}
		}
                //当tokens.keys为空时的注入
		else {
                        //这里得到一个BeanPropertyHandle的实例,这个类封装了PropertyDescription,关于PropertyDescription
                        //大家可以自行取了解下jdk的内省机制
                        PropertyHandler ph = getLocalPropertyHandler(actualName);
			//如果属性名为空或者属性无setter方法
                        if (ph == null || !ph.isWritable()) {
				//如果该值不是必须的就直接返回,否则抛出异常
                                if (pv.isOptional()) {
					if (logger.isDebugEnabled()) {
						logger.debug("Ignoring optional value for property '" + actualName +
								"' - property not found on bean class [" + getRootClass().getName() + "]");
					}
					return;
				}
				else {
					throw createNotWritablePropertyException(propertyName);
				}
			}
			Object oldValue = null;
			try {
				Object originalValue = pv.getValue();
				Object valueToApply = originalValue;
				if (!Boolean.FALSE.equals(pv.conversionNecessary)) {
					//如果属性中的值已经转换过
                                        if (pv.isConverted()) {
						valueToApply = pv.getConvertedValue();
					}
					else {
						if (isExtractOldValueForEditor() && ph.isReadable()) {
							try {
								//通过jdk的内省机制获取值
                                                                oldValue = ph.getValue();
							}
							catch (Exception ex) {
								if (ex instanceof PrivilegedActionException) {
									ex = ((PrivilegedActionException) ex).getException();
								}
								if (logger.isDebugEnabled()) {
									logger.debug("Could not read previous value of property '" +
											this.nestedPath + propertyName + "'", ex);
								}
							}
						}
						//获取转换后的属性值                        
                                                valueToApply = convertForProperty(
								propertyName, oldValue, originalValue, ph.toTypeDescriptor());
					}
					pv.getOriginalPropertyValue().conversionNecessary = (valueToApply != originalValue);
				}
				//将转换后的值注入到属性中
                                ph.setValue(this.wrappedObject, valueToApply);
			}
			catch (TypeMismatchException ex) {
				throw ex;
			}
			catch (InvocationTargetException ex) {
				PropertyChangeEvent propertyChangeEvent =
						new PropertyChangeEvent(this.rootObject, this.nestedPath + propertyName, oldValue, pv.getValue());
				if (ex.getTargetException() instanceof ClassCastException) {
					throw new TypeMismatchException(propertyChangeEvent, ph.getPropertyType(), ex.getTargetException());
				}
				else {
					Throwable cause = ex.getTargetException();
					if (cause instanceof UndeclaredThrowableException) {
						// May happen e.g. with Groovy-generated methods
						cause = cause.getCause();
					}
					throw new MethodInvocationException(propertyChangeEvent, cause);
				}
			}
			catch (Exception ex) {
				PropertyChangeEvent pce =
						new PropertyChangeEvent(this.rootObject, this.nestedPath + propertyName, oldValue, pv.getValue());
				throw new MethodInvocationException(pce, ex);
			}
		}
	}

在这里我比较疑惑的一点是,在以上方法中,如何能让代码进入tokens.keys!=null的分支中,我把所有集合类型包括数组都debug试了一遍,然而tokens.keys都为null,但是根据Spring技术内幕中的说明这个分支中进行的是对集合类型的注入,网上找的资料也没有什么明确的说明。获取tokens对象的方法在AbstractNestablePropertyAccessor的getPropertyNameTokens方法中,代码如下

private PropertyTokenHolder getPropertyNameTokens(String propertyName) {
		PropertyTokenHolder tokens = new PropertyTokenHolder();
		String actualName = null;
		List<String> keys = new ArrayList<String>(2);
		int searchIndex = 0;
		//这里截取属性名中"["、"]"之间的部分作为key保存到keys中
                while (searchIndex != -1) {
                        int keyStart = propertyName.indexOf(PROPERTY_KEY_PREFIX, searchIndex);
			searchIndex = -1;
			if (keyStart != -1) {
                                int keyEnd = propertyName.indexOf(PROPERTY_KEY_SUFFIX, keyStart + PROPERTY_KEY_PREFIX.length());
				if (keyEnd != -1) {
					if (actualName == null) {
						actualName = propertyName.substring(0, keyStart);
					}
                                        String key = propertyName.substring(keyStart + PROPERTY_KEY_PREFIX.length(), keyEnd);
					if (key.length() > 1 && (key.startsWith("'") && key.endsWith("'")) ||
							(key.startsWith("\"") && key.endsWith("\""))) {
						key = key.substring(1, key.length() - 1);
					}
					keys.add(key);
					searchIndex = keyEnd + PROPERTY_KEY_SUFFIX.length();
				}
			}
		}
		tokens.actualName = (actualName != null ? actualName : propertyName);
		tokens.canonicalName = tokens.actualName;
		if (!keys.isEmpty()) {
			tokens.canonicalName += PROPERTY_KEY_PREFIX +
					StringUtils.collectionToDelimitedString(keys, PROPERTY_KEY_SUFFIX + PROPERTY_KEY_PREFIX) +
					PROPERTY_KEY_SUFFIX;
			tokens.keys = StringUtils.toStringArray(keys);
		}
		return tokens;
	}

根据以上代码,如果tokens.keys不为空,那么解析的属性名称应该是形如propertyName[2]这种形式的,看起来应该是集合或者数组类型的属性,但是不知道怎样才能使属性名称解析成这种形式,这个问题后面我再试一试,希望有大神能够帮我解答。。

        至此,IOC容器对bean资源文件的定位,对bean的载入、解析以及依赖注入过程就完成了,下一篇我们来分析容器的其他相关特性的实现。

猜你喜欢

转载自blog.csdn.net/qq423196778/article/details/80680981