文档章节

Spring IoC核心实现

多弗哥
 多弗哥
发布于 2017/07/11 15:16
字数 6831
阅读 27
收藏 0

    Spring IoC核心有着庞大的继承、实现体系,众多的子接口、实现类,上一篇我们从源码入手,借助Spring 3.2官方API,简单的过了一遍,现在我们要来看看Spring IoC核心具体是怎么实现的了。

    简单来说,IoC容器的构建包含初始化和Bean依赖注入,IoC的初始化又可以分为Resource定位、BeanDefinition的载入和注册这三步。在Spring IoC的设计中,Bean的载入注册和依赖注入是两个独立的过程,前者发生在容器启动的时候,而后者发生在应用第一次通过getBean()方法获取Bean的时候 ①。

 

一、IoC容器的初始化

    IoC容器的初始化,是由前面介绍的AbstractApplicationContext#refresh()方法来启动整个调用的,这个方法详细地描述了整个ApplicationContext的初始化过程,比如BeanFactory的更新、PostProcessor的注册等,是IoC容器初始化的模板。refresh()方法的调用标志着容器初始化的开始。

@Override
public void refresh() throws BeansException, IllegalStateException {
	synchronized (this.startupShutdownMonitor) {
		// 准备刷新
		prepareRefresh();

		// 通知子类刷新上下文
		ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

		// 标准的上下文设置
		prepareBeanFactory(beanFactory);

		try {
			// 设置BeanFactory的后置处理器,默认空方法
			postProcessBeanFactory(beanFactory);

			// 调用BeanFactory的后置处理器,它们是必须在单例实例化之前调用
			invokeBeanFactoryPostProcessors(beanFactory);

			// 注册Bean后置处理器,在Bean创建过程中调用
			registerBeanPostProcessors(beanFactory);

			// 初始化上下文的消息源
			initMessageSource();

			// 初始化上下文中的事件机制
			initApplicationEventMulticaster();

			// 初始化其它特殊的Bean,默认为空
			onRefresh();

			// 注册监听器
			registerListeners();

			// 实例化剩下所有的non lazy-init单例
			finishBeanFactoryInitialization(beanFactory);

			// 发布容器事件,比如Lifecycle,并结束Refresh过程
			finishRefresh();

		} catch (BeansException ex) {
			// 销毁已创建的单例,避免Bean资源占用
			destroyBeans();
			// 重置'active'标识
			cancelRefresh(ex);

			throw ex;
		}
	}
}

    整个调用时序如图所示:

    

1、Resource定位

    Resource定位指的是BeanDefinition的资源定位,它由内部统一的资源加载接口(ResourceLoader)获得资源访问界面(Resource)。本质上这个定位过程就是IoC容器寻找资源的过程。

    部分代码调用清单:

  • AbstractApplicationContext
/**
 * BeanFactory刷新
 */
protected final void refreshBeanFactory() throws BeansException {
	// 如果已有存在,则销毁并关闭它,保证在refresh以后使用的是新建的IoC容器,类似于重启
	if (hasBeanFactory()) {
		destroyBeans();
		closeBeanFactory();
	}

	// 创建并持有DefaultListableBeanFactory
	// 同时,调用loadBeanDefinitions方法载入BeanDefinition信息
	try {
		DefaultListableBeanFactory beanFactory = createBeanFactory();
		beanFactory.setSerializationId(getId());
		customizeBeanFactory(beanFactory);

 		// 这里是调用的入口
		loadBeanDefinitions(beanFactory);

		synchronized (this.beanFactoryMonitor) {
			this.beanFactory = beanFactory;
		}
	} catch (IOException ex) {
		throw new ApplicationContextException(
		  "I/O error parsing bean definition source for " + getDisplayName(), ex);
	}
}

/**
 * 自定义内部的BeanFactory
 */
protected void customizeBeanFactory(DefaultListableBeanFactory beanFactory) {
	// 是否覆盖策略
	if (this.allowBeanDefinitionOverriding != null) {
		beanFactory.setAllowBeanDefinitionOverriding(this.allowBeanDefinitionOverriding);
	}
	// 循环引用策略
	if (this.allowCircularReferences != null) {
		beanFactory.setAllowCircularReferences(this.allowCircularReferences);
	}
	beanFactory.setAutowireCandidateResolver(new 
			QualifierAnnotationAutowireCandidateResolver());
}
  • AbstractRefreshableApplicationContext和AbstractXmlApplicationContext
/**
 * 通过XmlBeanDefinitionReader加载BeanDefinition
 */
protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) 
  throws BeansException, IOException {

	// 创建XmlBeanDefinitionReader,并通过回调设置到BeanFactory中去
	XmlBeanDefinitionReader beanDefinitionReader=new XmlBeanDefinitionReader(beanFactory);
	beanDefinitionReader.setEnvironment(this.getEnvironment());
	beanDefinitionReader.setResourceLoader(this);
	beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));

	initBeanDefinitionReader(beanDefinitionReader);
	// 继续加载BeanDefinition
	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);
	}
}
  • XmlBeanDefinitionReader
/**
 * 由给定的BeanFactory创建XmlBeanDefinitionReader
 */
public XmlBeanDefinitionReader(BeanDefinitionRegistry registry) {
	super(registry);
}

/**
 * 如果传入的BeanFactory不仅实现了BeanDefinitionRegistry接口,而且还实现了ResourceLoader接口,
 * 那么它将使用默认的ResourceLoader,这通常是ApplicationContext实现的情况。
 * 默认的ResourceLoader将是一个PathMatchingResourcePatternResolver。
 */
protected AbstractBeanDefinitionReader(BeanDefinitionRegistry registry) {

	Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
	this.registry = registry;

	// 确认是否使用ResourceLoader
	if (this.registry instanceof ResourceLoader) {
		this.resourceLoader = (ResourceLoader) this.registry;
	} else {
		this.resourceLoader = new PathMatchingResourcePatternResolver();
	}

	// 如果继承了EnvironmentCapable接口的话
	if (this.registry instanceof EnvironmentCapable) {
		this.environment = ((EnvironmentCapable) this.registry).getEnvironment();
	} else {
		this.environment = new StandardEnvironment();
	}
}

public int loadBeanDefinitions(String... locations) throws BeanDefinitionStoreException {
	Assert.notNull(locations, "Location array must not be null");

	// 统计
	int counter = 0;
	for (String location : locations) {
		counter += loadBeanDefinitions(location);
	}
	return counter;
}

public int loadBeanDefinitions(String location, Set<Resource> actualResources) 
  throws BeanDefinitionStoreException {

	// 取得前面设置的ResourceLoader
	ResourceLoader resourceLoader = getResourceLoader();
	if (resourceLoader == null) {
		throw new BeanDefinitionStoreException(
			"Cannot import bean definitions from location [" + location + 
				"]: no ResourceLoader available");
	}

	// 资源模式匹配,而后调用getResources()方法完成具体的Resource定位
	if (resourceLoader instanceof ResourcePatternResolver) {
		try {
			Resource[] resources=((ResourcePatternResolver)resourceLoader)
				.getResources(location);
			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 {
		// 只能通过绝对URL加载单个Resource资源
		Resource resource = resourceLoader.getResource(location);
		int loadCount = loadBeanDefinitions(resource);
		if (actualResources != null) {
			actualResources.add(resource);
		}
		if (logger.isDebugEnabled()) {
			logger.debug("Loaded " + loadCount + " bean definitions from location [" + 
				location + "]");
		}
		return loadCount;
	}
}

    具体的ResourceLoader如何从location或locationPattern中得到具体的Resource实现,ResourcePatternResolver接口如何解析我们设定的各种Ant格式的路径模式,感兴趣的同学可以从上面的调用链路继续往下追,这里就先不深入了。

 

2、BeanDefinition的载入和解析

    BeanDefinition的载入和解析,其实就是把用户配置好的Bean定义信息转化成Spring内部表示的数据结构的过程,而这个数据结构就是BeanDefinition。从流程上来看,在Resource定位完成的基础上,通过返回的Resource对象进行Bean定义信息的载入,然后按照Spring的Bean语义要求解析并转化成BeanDefinition对象。

    从上一节的调用链路中可以看到,我们实际使用的IoC容器是DefaultListableBeanFactory,具体的BeanDefinition的载入分为两部分,首先通过调用XML解析器得到通用的DOM对象,而后在默认创建的   DefaultBeanDefinitionDocumentReader中通过BeanDefinitionParserDelegate来完成对Document文档数内容的解析过程,返回的处理结果是由BeanDefinitionHolder来持有BeanDefinition对象的。

    部分代码调用清单:

  • XmlBeanDefinitionReader
/**
 * 从指定的资源加载BeanDefinition
 */
public int loadBeanDefinitions(Resource... resources) throws BeanDefinitionStoreException {
	// 如果Resource为空,则停止BeanDefinition载入
	Assert.notNull(resources, "Resource array must not be null");

	int counter = 0;
	for (Resource resource : resources) {
		counter += loadBeanDefinitions(resource);
	}
	return counter;
}

public int loadBeanDefinitions(EncodedResource encodedResource) 
  throws BeanDefinitionStoreException {

	// 在loadBeanDefinition过程中,首先输出的日志来自于这里
	Assert.notNull(encodedResource, "EncodedResource must not be null");
	if (logger.isInfoEnabled()) {
		logger.info("Loading XML bean definitions from " + encodedResource.getResource());
	}

	Set<EncodedResource> currentResources = this.resourcesCurrentlyBeingLoaded.get();
	if (currentResources == null) {
		currentResources = new HashSet<EncodedResource>(4);
		this.resourcesCurrentlyBeingLoaded.set(currentResources);
	}
	// 如果EncodedResource放入资源池失败
	if (!currentResources.add(encodedResource)) {
		throw new BeanDefinitionStoreException(
			"Detected cyclic loading of " + encodedResource + 
				" - check your import definitions!");
	}

	try {
		// IO读取,并包装成InputSource资源
		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();
		}
	}
}

/**
 * 这里是实际载入BeanDefinition的地方
 */
protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource)
  throws BeanDefinitionStoreException {
	try {
		// 获取验证模式
		int validationMode = getValidationModeForResource(resource);
		// 这里交给DefaultDocumentLoader去解析
		Document doc = this.documentLoader.loadDocument(
			inputSource, getEntityResolver(), this.errorHandler, validationMode,
				isNamespaceAware());
		// 启动对BeanDefinition的解析,这个解析过程涉及到了Spring的配置规则
		return registerBeanDefinitions(doc, resource);
	} catch (BeanDefinitionStoreException ex) {
		throw ex;
	} catch ....
}

/**
 * 注册给定DOM文档中包含的BeanDefinition
 */
public int registerBeanDefinitions(Document doc, Resource resource) 
  throws BeanDefinitionStoreException {
	// 创建BeanDefinitionDocumentReader实例,并在其上调用registerBeanDefinitions方法
	BeanDefinitionDocumentReader documentReader = createBeanDefinitionDocumentReader();
	documentReader.setEnvironment(getEnvironment());
	int countBefore = getRegistry().getBeanDefinitionCount();
	// 按照Spring的Bean定义规则进行解析,同时可以发现这里返回的是此次注册的Bean的个数(前后两次的差值)
	documentReader.registerBeanDefinitions(doc, createReaderContext(resource));
	return getRegistry().getBeanDefinitionCount() - countBefore;
}
  • DefaultBeanDefinitionDocumentReader
/**
 * 根据“spring-beans”XSD(或DTD)解析BeanDefinition
 * 而后打开DOM文档,首先初始化在<beans/>元素上指定的级别,再从给定的根<bean/>元素中注册每个bean定义
 */
@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) {
	String profileSpec = root.getAttribute(PROFILE_ATTRIBUTE);
	if (StringUtils.hasText(profileSpec)) {
		Assert.state(this.environment != null, 
			"Environment must be set for evaluating profiles");
		String[] specifiedProfiles = StringUtils.tokenizeToStringArray(profileSpec,
			BeanDefinitionParserDelegate.MULTI_VALUE_ATTRIBUTE_DELIMITERS);
		if (!this.environment.acceptsProfiles(specifiedProfiles)) {
			return;
		}
	}

	// 任何嵌套的<beans>元素都将导致此方法中的递归
	BeanDefinitionParserDelegate parent = this.delegate;
	this.delegate = createDelegate(this.readerContext, root, parent);

	preProcessXml(root);
	parseBeanDefinitions(root, this.delegate);
	postProcessXml(root);
	this.delegate = parent;
}

/**
 * 解析文档中根级别的元素:"import", "alias", "bean".
 */
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)) {
		doRegisterBeanDefinitions(ele);
	}
}

/**
 * 解析BeanDefinition并将其注册到注册表。
 */
protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) {

	//对DOM的处理委托给BeanDefinitionParserDelegate,Element对应于在在Spring Bean定义中的XML元素
	// 解析的结果由BeanDefinitionHolder对象来持有。
	BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);
	if (bdHolder != null) {
		bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);
		try {
			// 这里是向IoC容器注册解析得到的、最终修饰的BeanDefinition的地方
			BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, 
				getReaderContext().getRegistry());
		} catch (BeanDefinitionStoreException ex) {
			getReaderContext().error("Failed to register bean definition with name '" +
					bdHolder.getBeanName() + "'", ele, ex);
		}
		// 发送注册事件
		getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder));
	}
}
  • BeanDefinitionParserDelegate
/**
 * 这个方法包含了对Bean元素的处理,比如id、name、aliase等属性元素的处理
 * 把这些元素的值从XML文件相应的元素的属性中读出来之后,设置到生成的BeanDefinitionHolder中去
 */
public BeanDefinitionHolder parseBeanDefinitionElement(Element ele, 
  BeanDefinition containingBean) {
	// 取得在<bean>元素中定义的id、name属性值
	String id = ele.getAttribute(ID_ATTRIBUTE);
	String nameAttr = ele.getAttribute(NAME_ATTRIBUTE);

	List<String> aliases = new ArrayList<String>();
	if (StringUtils.hasLength(nameAttr)) {
		String[] nameArr = StringUtils.tokenizeToStringArray(nameAttr, 
			MULTI_VALUE_ATTRIBUTE_DELIMITERS);
		aliases.addAll(Arrays.asList(nameArr));
	}

	String beanName = id;
	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");
		}
	}
	if (containingBean == null) {
		checkNameUniqueness(beanName, aliases, ele);
	}

	// 对bean元素详细解析的入口
	AbstractBeanDefinition beanDefinition = parseBeanDefinitionElement(ele, 
		beanName, containingBean);
	if (beanDefinition != null) {
		if (!StringUtils.hasText(beanName)) {
			try {
				if (containingBean != null) {
					beanName = BeanDefinitionReaderUtils.generateBeanName(
							beanDefinition, this.readerContext.getRegistry(), true);
				} else {
					beanName = this.readerContext.generateBeanName(beanDefinition);
					// 如果生成器返回的类名可用
					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;
}

public AbstractBeanDefinition parseBeanDefinitionElement(
		Element ele, String beanName, BeanDefinition containingBean) {
	this.parseState.push(new BeanEntry(beanName));

	// 只读取<bean>定义中的class属性,并不涉及对象的实例化过程
	String className = null;
	if (ele.hasAttribute(CLASS_ATTRIBUTE)) {
		className = ele.getAttribute(CLASS_ATTRIBUTE).trim();
	}

	try {
		String parent = null;
		if (ele.hasAttribute(PARENT_ATTRIBUTE)) {
			parent = ele.getAttribute(PARENT_ATTRIBUTE);
		}
		// 生成BeanDefinition对象,为Bean定义信息载入做准备
		AbstractBeanDefinition bd = createBeanDefinition(className, parent);
		// 对当前的bean元素的属性进行解析,并设置description
		parseBeanDefinitionAttributes(ele, beanName, containingBean, bd);
		bd.setDescription(DomUtils.getChildElementValueByTagName(ele,DESCRIPTION_ELEMENT));

		// 对各种<bean>元素进行解析
		parseMetaElements(ele, bd);
		parseLookupOverrideSubElements(ele, bd.getMethodOverrides());
		parseReplacedMethodSubElements(ele, bd.getMethodOverrides());
		// <bean>的构造函数
		parseConstructorArgElements(ele, bd);
		// <bean>的字段设置
		parsePropertyElements(ele, bd);
		parseQualifierElements(ele, bd);
		bd.setResource(this.readerContext.getResource());
		bd.setSource(extractSource(ele));
		return bd;

	// 这些异常是在配置Bean时常出现,大部分是在createBeanDefinition()里抛出的
	} 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;
}

// ------------------------------------------------------------------------
// 比如对字段属性值的处理,会被封装成PropertyValue对象并设置到BeanDefinition对象中去
public void parsePropertyElements(Element beanEle, BeanDefinition bd) {
	NodeList nl = beanEle.getChildNodes();
	// 遍历所有Bean元素下定义的property元素
	for (int i = 0; i < nl.getLength(); i++) {
		Node node = nl.item(i);
		if (isCandidateElement(node) && nodeNameEquals(node, PROPERTY_ELEMENT)) {
			parsePropertyElement((Element) node, bd);
		}
	}
}

public void parsePropertyElement(Element ele, BeanDefinition bd) {
	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 {
		// 如果同一个Bean中已经有同名的property存在,则不进行解析直接返回
		// 那么也就是说,这种情况下起作用的只有第一个
		if (bd.getPropertyValues().contains(propertyName)) {
			error("Multiple 'property' definitions for property '" + 
				propertyName + "'", ele);
			return;
		}
		// 解析property值,返回对应Bean定义中property属性设置的解析结果
		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, String propertyName) {
	String elementName = (propertyName != null) ?
					"<property> element for property '" + propertyName + "'" :
					"<constructor-arg> element";

	// 应该只有一个子元素: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,不允许同时存在
	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,创建一个ref对应的数据对象 RuntimeBeanReference
	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,创建一个value对应的数据对象 TypedStringValue
	else if (hasValueAttribute) {
		TypedStringValue valueHolder = new TypedStringValue(ele.
			getAttribute(VALUE_ATTRIBUTE));
		valueHolder.setSource(extractSource(ele));
		return valueHolder;
	}
	// 如果还有子元素,触发对子元素的解析
	else if (subElement != null) {
		// 对property子元素的解析过程,各种Array、List、Set、Map等元素会在这个方法里被解析,
		// 生成对应的数据对象,比如ManagedArray、ManagedList、ManagedSet、ManagedMap等,
		// 这些Managed类是Spring对具体的BeanDefinition的数据封装
		return parsePropertySubElement(subElement, bd);
	} else {
		// 找不到子元素和“ref”或“value”属性
		error(elementName + " must specify a ref or value", ele);
		return null;
	}
}

    就是这样,逐层逐层地对Bean定义中的定义数据进行解析,从属性元素集合到具体的每一个属性元素,再到具体的属性值的处理,我们在XML文件中定义BeanDefinition就被整个载入到了IoC容器中去,并在容器中建立了对应的数据结构,或者说POJO对象在IoC容器中的抽象。

 

3、BeanDefinition注册

    在前面的这些载入、解析动作完成以后,用户定义的BeanDefinition信息已经在IoC容器内建立起了自己的数据结构以及相应的数据表示,但此时这些数据还不能供IoC容器直接使用,这就需要在IoC容器中对这些BeanDefinition对象进行注册了。

    它通过调用BeanDefinitionRegistry接口实现来完成的。简单来说,这个过程就是把载入过程中解析得到的BeanDefinition向IoC容器进行注册的过程,实质上就是交由DefaultListableBeanFactory中通过ConcurrentHashMap来持有这些BeanDefinition对象。需要注意的是,如果遇到同名的BeanDefinition,需要根据allowBeanDefinitionOverriding(是否允许覆盖)属性值来进行判断。

    完成了BeanDefinition的注册,就完了IoC容器的初始化过程,此时,在使用的IoC容器中已经建立起整个Bean的配置信息,且都已经准备好被容器使用了,这些信息是IoC容器建立依赖反转的基础。

/**
 * 使用此注册表注册新的bean定义
 */
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);
		}
	}

	// 注册的过程需要synchronized,保证数据的一致性
	BeanDefinition oldBeanDefinition;
	synchronized (this.beanDefinitionMap) {
		oldBeanDefinition = this.beanDefinitionMap.get(beanName);
		// 如果存在同名的BeanDefinition,又不允许覆盖,则抛错
		if (oldBeanDefinition != null) {
			if (!this.allowBeanDefinitionOverriding) {
				throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(),
					beanName, "Cannot register bean definition [" + 
					beanDefinition + "] for bean '" + beanName + "': There is already ["
					+ oldBeanDefinition + "] bound.");
			} else {
				if (this.logger.isInfoEnabled()) {
					this.logger.info("Overriding bean definition for bean '" + beanName +
						"': replacing [" + oldBeanDefinition + "] with [" + 
						beanDefinition + "]");
				}
			}
		} else {
			// 正常注册BeanDefinition的过程:将beanName存进beanDefinitionNames,
			// 并把BeanDefinition存入注册表中
			this.beanDefinitionNames.add(beanName);
			this.frozenBeanDefinitionNames = null;
		}
		this.beanDefinitionMap.put(beanName, beanDefinition);
	}

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

 

二、IoC容器的依赖注入

    上一小节,我们看到了IoC容器的初始化,它的主要工作是在IoC容器中建立BeanDefinition数据映射,那么IoC容器是怎么注入Bean的依赖关系的呢?

    首先,依赖注入的过程是用户第一次想IoC容器getBean时触发的(除了Bean的预实例化),就是调用IoC容器的根接口BeanFactory#getBean()方法时,它是一个重载方法,不管具体是调用哪个getBean方法最终都是通过调用doGetBean()方法来实现的。

  • AbstractBeanFactory
/*
 * 实际获取Bean实例的方法
 */
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;

	// 先从单例缓存中获取Bean
	Object sharedInstance = getSingleton(beanName);
	if (sharedInstance != null && args == null) {
		if (logger.isDebugEnabled()) {
			// 判断指定的单例bean是否正在创建
			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 + "'");
			}
		}
		// 
		bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);

	} else {
		// 判断指定的原型bean当前是否在创建
		if (isPrototypeCurrentlyInCreation(beanName)) {
			throw new BeanCurrentlyInCreationException(beanName);
		}

		// 检查此工厂中是否存在bean定义
		BeanFactory parentBeanFactory = getParentBeanFactory();
		if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
			// 如果当前BeanFactory未找到 -> 委托给父BeanFactory去查找
			String nameToLookup = originalBeanName(name);
			if (args != null) {
				return (T) parentBeanFactory.getBean(nameToLookup, args);
			} else {
				// 没有args -> 委托给标准的getBean方法
				return parentBeanFactory.getBean(nameToLookup, requiredType);
			}
		}

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

		try {
			final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
			checkMergedBeanDefinition(mbd, beanName, args);

			// 获取当前Bean的所有依赖Bean,触发getBean的递归调用
			String[] dependsOn = mbd.getDependsOn();
			if (dependsOn != null) {
				for (String dependsOnBean : dependsOn) {
					getBean(dependsOnBean);
					// 注册依赖bean
					registerDependentBean(dependsOnBean, beanName);
				}
			}

			// 创建bean实例
			if (mbd.isSingleton()) {
				sharedInstance = getSingleton(beanName, new ObjectFactory<Object>() {
					public Object getObject() throws BeansException {
						try {
							return createBean(beanName, mbd, args);
						} catch (BeansException ex) {
							// 删除单例缓存中的实例,以及对该bean引用的任何bean
							destroySingleton(beanName);
							throw ex;
						}
					}
				});
				bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);

			} else if (mbd.isPrototype()) {
				// 创建一个新的原型实例
				Object prototypeInstance = null;
				try {
					beforePrototypeCreation(beanName);
					prototypeInstance = createBean(beanName, mbd, args);
				}
				finally {
					afterPrototypeCreation(beanName);
				}
				bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);

			} else {
				// 在BeanDefinition的注册范围内创建一个新实例
				String scopeName = mbd.getScope();
				final Scope scope = this.scopes.get(scopeName);
				if (scope == null) {
					throw new IllegalStateException("No Scope registered for scope '" + 
					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;
		}
	}

	// 对创建的Bean进行类型检查:所需类型是否与实际bean实例的类型相匹配
	// 此时这个Bean,已经是包含了依赖关系的Bean实例对象了
	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;
}

/**
 * 返回以给定名称注册的(原始)单例对象
 */
protected Object getSingleton(String beanName, boolean allowEarlyReference) {
	Object singletonObject = this.singletonObjects.get(beanName);
	if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
		synchronized (this.singletonObjects) {
			singletonObject = this.earlySingletonObjects.get(beanName);
			if (singletonObject == null && allowEarlyReference) {
				ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
				if (singletonFactory != null) {
					singletonObject = singletonFactory.getObject();
					this.earlySingletonObjects.put(beanName, singletonObject);
					this.singletonFactories.remove(beanName);
				}
			}
		}
	}
	return (singletonObject != NULL_OBJECT ? singletonObject : null);
}

/**
 * 完成FactoryBean的处理,返回FactoryBean的生产结果————bean实例的对象
 */
protected Object getObjectForBeanInstance(  
		Object beanInstance, String name, String beanName, RootBeanDefinition mbd) {  

	//如果是对FactoryBean的引用,且bean对象不是FactoryBean,则抛出异常  
	if (BeanFactoryUtils.isFactoryDereference(name)&&!(beanInstance instanceof FactoryBean){  
		throw new BeanIsNotAFactoryException(transformedBeanName(name),
			beanInstance.getClass());  
	}

	//如果Bean实例不是FactoryBean或是FactoryBean,即是普通的bean调用,则直接返回当前的Bean实例    
	if (!(beanInstance instanceof FactoryBean)||BeanFactoryUtils.isFactoryDereference(name){  
		return beanInstance;  
	}  

	//处理对FactoryBean的调用  
	Object object = null;  
	if (mbd == null) {  
		//从Bean工厂缓存中获取给定名称的实例对象  
		object = getCachedObjectForFactoryBean(beanName);  
	}  
	if (object == null) {  
		// Return bean instance from factory.  
		FactoryBean factory = (FactoryBean) beanInstance;  
		//如果从Bean工厂生产的Bean是单例模式的,则缓存  
		if (mbd == null && containsBeanDefinition(beanName)) {  
			mbd = getMergedLocalBeanDefinition(beanName);  
		}  
		boolean synthetic = (mbd != null && mbd.isSynthetic());  
		//调用FactoryBeanRegistrySupport#getObjectFromFactoryBean方法,
		//实现FactoryBean生产Bean对象实例的过程    
		object = getObjectFromFactoryBean(factory, beanName, !synthetic);  
	}  
	return object;  
}

/**
 * Bean工厂生产Bean实例对象  
 */
protected Object getObjectFromFactoryBean(FactoryBean factory, String beanName,
		boolean shouldPostProcess) {  
	// Bean工厂是单态模式,并且Bean工厂缓存中存在指定名称的Bean实例对象  
	if (factory.isSingleton() && containsSingleton(beanName)) {  
		synchronized (getSingletonMutex()) {  
			// 直接从Bean工厂缓存中获取指定名称的Bean实例对象  
			Object object = this.factoryBeanObjectCache.get(beanName);  
			// Bean工厂缓存中没有指定名称的实例对象,则生产该实例对象  
			if (object == null) {  
				// 调用Bean工厂的getObject方法生产指定Bean的实例对象  
				object = doGetObjectFromFactoryBean(factory, beanName, shouldPostProcess);  
				// 将生产的实例对象添加到Bean工厂缓存中
				this.factoryBeanObjectCache.put(beanName,
					(object != null ? object : NULL_OBJECT));  
			}
			return (object != NULL_OBJECT ? object : null);  
		}  
	} else {  
		// 调用Bean工厂的getObject方法生产指定Bean的实例对象  
		return doGetObjectFromFactoryBean(factory, beanName, shouldPostProcess);  
	}  
}  

/**
 * 调用Bean工厂的getObject方法生产指定Bean的实例对象    
 */
private Object doGetObjectFromFactoryBean(final FactoryBean factory,final String beanName,
		final boolean shouldPostProcess) throws BeanCreationException {    
	Object object;    
	try {    
		if (System.getSecurityManager() != null) {    
			AccessControlContext acc = getAccessControlContext();    
			try {    
				//实现PrivilegedExceptionAction接口的匿名内置类    
				//根据JVM检查权限,然后决定BeanFactory创建实例对象    
				object = AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
					public Object run() throws Exception {    
						//调用BeanFactory接口实现类的创建对象方法    
						return factory.getObject();    
					}    
				}, acc);    
			} catch (PrivilegedActionException pae) {    
				throw pae.getException();    
			}    
		} else {    
			//调用BeanFactory接口实现类的创建对象方法    
			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);    
	}    

	//创建出来的实例对象为null,或者因为单态对象正在创建而返回null    
	if (object == null && isSingletonCurrentlyInCreation(beanName)) {    
		throw new BeanCurrentlyInCreationException( beanName, 
			"FactoryBean which is currently in creation returned null from getObject");    
	}    
	//为创建出来的Bean实例对象添加BeanPostProcessor后置处理器    
	if (object != null && shouldPostProcess) {    
		try {    
			object = postProcessObjectFromFactoryBean(object, beanName);    
		} catch (Throwable ex) {    
			throw new BeanCreationException(beanName, 
				"Post-processing of the FactoryBean's object failed", ex);    
		}    
	}    
	return object;    
}   
  • AbstractAutowireCapableBeanFactory
protected Object createBean(final String beanName, final RootBeanDefinition mbd,
	final Object[] args) throws BeanCreationException {
	if (logger.isDebugEnabled()) {
		logger.debug("Creating instance of bean '" + beanName + "'");
	}

	// 解决Bean是否可以实例化,是否可以通过类装载器来载入
	resolveBeanClass(mbd, beanName);
	// 准备方法覆盖
	try {
		mbd.prepareMethodOverrides();
	} catch (BeanDefinitionValidationException ex) {
		throw new BeanDefinitionStoreException(mbd.getResourceDescription(),
			beanName, "Validation of method overrides failed", ex);
	}

	try {
		// 如果Bean配置了BeanPostProcessors,那么这里返回的是一个Proxy
		Object bean = resolveBeforeInstantiation(beanName, mbd);
		if (bean != null) {
			return bean;
		}
	} catch (Throwable ex) {
		throw new BeanCreationException(mbd.getResourceDescription(), beanName,
			"BeanPostProcessor before instantiation of bean failed", ex);
	}

	// 创建Bean
	Object beanInstance = doCreateBean(beanName, mbd, args);
	if (logger.isDebugEnabled()) {
		logger.debug("Finished creating instance of bean '" + beanName + "'");
	}
	return beanInstance;
}

/**
 * 实际创建指定的bean,此时已经发生了预创建处理
 * 区分默认bean实例化,使用工厂方法和自动连接构造函数
 */
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd,
		final Object[] args) {
	// 使用BeanWrapper 来持有新创建出来的Bean对象
	BeanWrapper instanceWrapper = null;
	// 如果是Singleton,则先把缓存中的同名Bean清除,而后创建Bean
	if (mbd.isSingleton()) {
		instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
	}
	if (instanceWrapper == null) {
		instanceWrapper = createBeanInstance(beanName, mbd, args);
	}
	final Object bean=(instanceWrapper!=null?instanceWrapper.getWrappedInstance():null);
	Class<?> beanType=(instanceWrapper!=null?instanceWrapper.getWrappedClass():null);

	// 允许后处理器修改合并的bean定义
	synchronized (mbd.postProcessingLock) {
		if (!mbd.postProcessed) {
			applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
			mbd.postProcessed = true;
		}
	}

	// 高速缓存单例来解析循环引用
	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>() {
			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) {
		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<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;
}

/**
 * 创建指定bean的新实例
 */
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());
	}
	// 使用工厂方法对Bean进行实例化
	if (mbd.getFactoryMethodName() != null)  {
		return instantiateUsingFactoryMethod(beanName, mbd, args);
	}

	// 重新创建同一个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);
	}

	// 使用默认的构造函数对Bean进行实例化
	return instantiateBean(beanName, mbd);
}

/**
 * 使用默认的构造函数对Bean进行实例化
 */
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>(){
				public Object run() {
					return 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);
	}
}


// ------------------------- 设置依赖关系 -----------------------------------
/**
 * 使用bean定义中的属性值填充给定BeanWrapper中的bean实例
 */
protected void populateBean(String beanName, RootBeanDefinition mbd, BeanWrapper bw) {

	// 获取BeanDefinition中设置的property值,这来自对BeanDefinition的解析
	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;
		}
	}

	// 如果配置了InstantiationAwareBeanPostProcessor,那么这里执行它去修改bean状态
	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;
	}
	// 开始进行依赖注入过程,先处理autowire的注入
	if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME ||
			mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
		MutablePropertyValues newPvs = new MutablePropertyValues(pvs);

		// 对autowire注入的处理:通过名称添加基于autowire的属性值
		if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME) {
			autowireByName(beanName, mbd, bw, newPvs);
		}
		// 对autowire注入的处理:根据类型添加基于autowire的属性值
		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);
}

/**
 * 对属性进行解析然后注入
 */
protected void applyPropertyValues(String beanName, BeanDefinition mbd, BeanWrapper bw,
		PropertyValues pvs) {
	if (pvs == null || pvs.isEmpty()) {
		return;
	}

	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;
		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();
	} else {
		original = Arrays.asList(pvs.getPropertyValues());
	}

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

	// 为解析值创建一个深层副本,解析任何值的引用
	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));
			}
		}
	}
	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);
	}
}
  • SimpleInstantiationStrategy
public Object instantiate(RootBeanDefinition beanDefinition, String beanName,
		BeanFactory owner) {

	// 如果没有覆盖,不要用CGLIB覆盖类
	if (beanDefinition.getMethodOverrides().isEmpty()) {
		Constructor<?> constructorToUse;
		synchronized (beanDefinition.constructorArgumentLock) {
			// 获取指定的构造函数或生成对象的工厂方法来对Bean进行实例化
			constructorToUse=(Constructor<?>)beanDefinition.resolvedConstructorOrFactoryMethod;
			if (constructorToUse == null) {
				final Class<?> clazz = beanDefinition.getBeanClass();
				if (clazz.isInterface()) {
					throw new BeanInstantiationException(clazz, 
						"Specified class is an interface");
				}
				try {
					if (System.getSecurityManager() != null) {
						constructorToUse = AccessController.doPrivileged(
							new PrivilegedExceptionAction<Constructor>() {
							public Constructor<?> run() throws Exception {
								return clazz.getDeclaredConstructor((Class[]) null);
							}
						});
					} else {
						constructorToUse=clazz.getDeclaredConstructor((Class[]) null);
					}
					beanDefinition.resolvedConstructorOrFactoryMethod = constructorToUse;
				} catch (Exception ex) {
					throw new BeanInstantiationException(clazz, 
						"No default constructor found", ex);
				}
			}
		}
		// 这个BeanUtils的实例化实际上也是通过Constructor来进行实例化的
		return BeanUtils.instantiateClass(constructorToUse);
	} else {
		// 使用CGLIB来进行实例化对象
		return instantiateWithMethodInjection(beanDefinition, beanName, owner);
	}
}

    在Bean的创建和对象依赖注入的过程中,需要依据容器中的BeanDefinition已经建立好的信息来递归完成依赖关系的注入。这些递归都是以getBean方法为入口的。一个递归是在上下文体系中查找需要的Bean和创建Bean的递归调用;另一个递归是在依赖注入时,通过递归调用容器的getBean方法得到当前Bean的依赖Bean,同时也触发了对依赖Bean的创建和注入。在对Bean属性进行依赖注入时,解析的过程同样也是一个递归的过程。就这样子,根据依赖关系,逐层逐层地完成Bean的创建和注入,直到最后完成当前Bean的创建。有了这个顶层Bean的创建和对它属性的依赖注入的完成,意味着和当前Bean相关的整个依赖链的注入也都完成了。

    在Bean创建和依赖注入完成以后,就在IoC容器中建立起一系列依靠依赖关系联系起来的Bean,这个Bean系列以及Bean之间的依赖关系,通过IoC容器的相关接口方法,就可以非常方便的供上层建筑使用。

 

 

注:

    ① 这里有个例外,就是预实例化配置。用户可以通过<bean>元素中的lazy-init属性来进行设置,那么这个被设置了lazy-init的Bean的依赖注入过程在IoC容器初始化时就预先完成了,而不用等到整个初始化完成以后,第一次使用getBean时才触发。

 

© 著作权归作者所有

多弗哥
粉丝 16
博文 44
码字总数 158896
作品 0
杭州
高级程序员
私信 提问
三条路线告诉你如何掌握Spring IoC容器的核心原理

一、前言 前三篇已经从历史的角度和大家一起探讨了为什么会有Spring,Spring的两个核心概念:IoC和AOP的雏形,Spring的历史变迁和如今的生态帝国。本节的主要目的就是通过一个切入点带大家一...

Java小铺
2018/08/27
0
0
Spring IoC(更新中)

概念 IoC(控制反转,也叫依赖注入DI)是Spring的核心,几乎Spring的所有组件都要建立在此基础之上,包括AOP,声明式事务,SpringMVC等等。那么IoC的主要目的是什么呢?两个字“解耦”。为什么...

互联网小龙虾
2014/03/04
156
0
在spring中如何配置和使用一个Bean

在Spring中,那些组成你应用程序的主体(backbone)及由Spring IoC容器所管理的对象,被称之为bean。 简单地讲,bean就是由Spring容器初始化、装配及管理的对象,除此之外,bean就与应用程序中...

冰雷卡尔
2012/07/24
189
0
Spring 的基本应用:IoC 和 AOP

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。 https://blog.csdn.net/GitChat/article/details/97292080 前言spring 对于任何一个 Java 开...

GitChat技术杂谈
07/25
0
0
1 Spring核心:IoC容器的实现

依赖控制反转的实现有很多种方式。在Spring中,IoC容器是实现这个模式的载体, 它可以在对象生成或初始化时直接将数据注入到对象中,也可以通过将对象引用注入到对象数据域中的方式来注入对方...

qq_18150351
2018/04/24
0
0

没有更多内容

加载失败,请刷新页面

加载更多

手写RPC框架指北另送贴心注释代码一套

Angular8正式发布了,Java13再过几个月也要发布了,技术迭代这么快,框架的复杂度越来越大,但是原理是基本不变的。所以沉下心看清代码本质很重要,这次给大家带来的是手写RPC框架。 完整代码...

全菜工程师小辉
12分钟前
2
0
【Java】开发收货

简介 谨以此篇,记载开发过程中的一些tips。 编译器 【Shift + F6】可实现变量的联动修改。

Areya
29分钟前
5
0
DOM官方定义

DOM Document Object Model 文档对象模型 DOM的官方定义:W3C的DOM,可以使程序或者脚本(JS或AS\JScript),动态的访问或者操作文档的内容、结构、样式。 DOM只是一个标准,操作网页的标准。...

前端老手
35分钟前
6
0
IT兄弟连 HTML5教程 HTML5的学习线路图 第一阶段学习网页制作

学习HTML5技术可并不是简单学会几个新增的标签而已,HTML5现在可以说是前端所有技术的代名词。需要学习的语言和工具不仅多,对于刚接触他们的新人会感觉很乱。另外,前端开发也会细分很多个开...

老码农的一亩三分地
36分钟前
6
0
可见性有序性,Happens-before来搞定

写在前面 上一篇文章并发 Bug 之源有三,请睁大眼睛看清它们 谈到了可见性/原子性/有序性三个问题,这些问题通常违背我们的直觉和思考模式,也就导致了很多并发 Bug 为了解决 CPU,内存,IO ...

tan日拱一兵
52分钟前
4
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部