小明学Spring Framework容器启动系列——Bean定义的解析


系列文章——小明学Spring Framework容器启动系列
1. 小明学Spring Framework容器启动系列——Spring Framework容器启动概览2. 小明学Spring Framework容器启动系列——Bean定义的读取
3. 小明学Spring Framework容器启动系列——Bean定义的解析4.小明学Spring Framework容器启动系列——Bean名称生成策略
5.小明学Spring Framework容器启动系列——Bean定义的注册6.小明学Spring Framework容器启动系列——容器PrepareRefresh
7.小明学Spring Framework容器启动系列——BeanFactory的初始化8.小明学Spring Framework容器启动系列——BeanPostProcessor和BeanFactoryPostProcessor的初始化
9.小明学Spring Framework容器启动系列——国际化与事件的初始化10.小明学Spring Framework容器启动系列——BeanFactory的初始化完成
11. 小明学Spring Framework容器启动系列——容器启动的收尾工作

1. 前言

1. 前言

读取本文之前,大家应该知道什么是Bean定义,在我的另外一篇博客中有详细介绍。
Spring容器的构建过程是自动化的,意味着用户写好容器的定义之后,Spring容器可以自动根据用户的定义装配好容器。在我的另外一篇博客中,简述了如何读取Spring的xml文件和注解定义,但是读取到的定义以资源(二进制数据流)的形式存在,还需要解析为Spring容器的定义,才能被Spring容器识别。Bean定义的解析在整个Spring容器启动过程中的位置如图中的红色方框部分所示。

在这里插入图片描述

2. XML定义解析

下面代码为一个常见的Spring容器的xml定义形式,如果Spring指定这个XML为容器定义,那么容器启动之后里边会包含一个TestBean的实例Bean,那么Spring是如何解析这个xml文件的呢?这就是本节的重点内容。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd">
    
    <bean id="test" class="com.test.TestBean"></bean>
</beans>

假设此xml配置文件位于resource目录之下,名称为spring.xml,那么我们根据这个xml文件生成Spring容器的语句示例如下,该语句执行完之后,spring容器就构建完成并且包含了一个TestBean的实例Bean,下文我们将分步骤介绍Spring如何将XML文件解析为Bean定义的,本节不会讲Bean的实例化。

ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
// Here the context is prepared.

2.1 XML文件的读取

在启动Spring容器的时候,我们只指定了一个文件路径,那么Spring是如何查找并读取这个文件的呢?大家可以参考我的另外一篇博客,里面简述了Spring资源管理相关的内容。通过Spring资源加载器我们可以获取resource目录下的指定文件,并读取为二进制数据流,此处不做详细解释。Spring读取xml文件的AbstractBeanDefinitionReader部分源码如下:

	/**
	 * Load bean definitions from the specified resource location.
	 * <p>The location can also be a location pattern, provided that the
	 * ResourceLoader of this bean definition reader is a ResourcePatternResolver.
	 * @param location the resource location, to be loaded with the ResourceLoader
	 * (or ResourcePatternResolver) of this bean definition reader
	 * @param actualResources a Set to be filled with the actual Resource objects
	 * that have been resolved during the loading process. May be {@code null}
	 * to indicate that the caller is not interested in those Resource objects.
	 */
	public int loadBeanDefinitions(String location, @Nullable Set<Resource> actualResources) throws BeanDefinitionStoreException {
		ResourceLoader resourceLoader = getResourceLoader();
		if (resourceLoader == null) {
			throw new BeanDefinitionStoreException(
					"Cannot load bean definitions from location [" + location + "]: no ResourceLoader available");
		}

		if (resourceLoader instanceof ResourcePatternResolver) {
			// Resource pattern matching available.
			try {
				Resource[] resources = ((ResourcePatternResolver) resourceLoader).getResources(location);
				// do someting with resource
			}
		}
		else {
			// Can only load single resources by absolute URL.
			Resource resource = resourceLoader.getResource(location);
			// do someting with resource
		}
	}

2.2 XML文件节点解析

通过Spring资源加载器读取xml文件,读取到的只是一个输入流,并没有解析为xml节点,Spring中使用了java的org.w3c.dom库,把Spring文件读取为对应的节点树。Spring使用w3c解析xml数据流的源代码DefaultDocumentLoader如下所示:


	/**
	 * Load the {@link Document} at the supplied {@link InputSource} using the standard JAXP-configured
	 * XML parser.
	 */
	@Override
	public Document loadDocument(InputSource inputSource, EntityResolver entityResolver,
			ErrorHandler errorHandler, int validationMode, boolean namespaceAware) throws Exception {

		DocumentBuilderFactory factory = createDocumentBuilderFactory(validationMode, namespaceAware);
		if (logger.isTraceEnabled()) {
			logger.trace("Using JAXP provider [" + factory.getClass().getName() + "]");
		}
		DocumentBuilder builder = createDocumentBuilder(factory, entityResolver, errorHandler);
		return builder.parse(inputSource);
	}

2.3 w3c文档转Spring容器定义

通过步骤2,我们把Spring的xml文档读取为一个w3c库中的Document格式的对象,接下来Spring会按照节点树一层一层的解析这些节点,Spring中解析这些节点的主要代码在DefaultBeanDefinitionDocumentReader中,解析主要流程如下:

  1. 判断xml节点namespace的uri是否为空或者http://www.springframework.org/schema/beans,并处理profiles属性;
  2. 遍历当前节点的所有子节点,处理beans、alias、import等属性;
  3. 处理节点的子节点,如bean解析为BeanDefinition

2.4 总结

通过以上步骤,Spring会把xml文档转为Spring内部可以直接使用的Bean对象,方便后文中继续使用。

3. 注解定义解析

由于SpringBoot是近些年来使用比较多的框架,并且Springboot是基于注解进行容器定义的,所以Spring注解定义是近些年来使用比较多的配置方式,Spring注解的的读取大多数是通过扫描包的形式进行的,用户可以按照如下方式定义一个Spring的Bean:

package com.xxx;

@Component
public class ComponentDemo{
}

然后用户可以通过如下语句加载对应的组件:

AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext("com.xxx");
   // Here the context is prepared.

那么Spring是如何根据一个包名加载对应的定义的呢?分析Spring的ClassPathBeanDefinitionScanner中的源码可以发现Spring依旧是通过资源加载器ResourceLoader扫描class文件,然后在其中查找包含特定注解的类(如Spring的@Component和JSR的ManagedBean等),Spring扫描BeanClassPathBeanDefinitionScanner的部分源码如下所示:


	/**
	 * Perform a scan within the specified base packages,
	 * returning the registered bean definitions.
	 * <p>This method does <i>not</i> register an annotation config processor
	 * but rather leaves this up to the caller.
	 */
	protected Set<BeanDefinitionHolder> doScan(String... basePackages) {
		Assert.notEmpty(basePackages, "At least one base package must be specified");
		Set<BeanDefinitionHolder> beanDefinitions = new LinkedHashSet<>();
		for (String basePackage : basePackages) {
			Set<BeanDefinition> candidates = findCandidateComponents(basePackage);
			for (BeanDefinition candidate : candidates) {
				ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(candidate);
				candidate.setScope(scopeMetadata.getScopeName());
				String beanName = this.beanNameGenerator.generateBeanName(candidate, this.registry);
				if (candidate instanceof AbstractBeanDefinition) {
					postProcessBeanDefinition((AbstractBeanDefinition) candidate, beanName);
				}
				if (candidate instanceof AnnotatedBeanDefinition) {
					AnnotationConfigUtils.processCommonDefinitionAnnotations((AnnotatedBeanDefinition) candidate);
				}
				if (checkCandidate(beanName, candidate)) {
					BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(candidate, beanName);
					definitionHolder =
							AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
					beanDefinitions.add(definitionHolder);
					registerBeanDefinition(definitionHolder, this.registry);
				}
			}
		}
		return beanDefinitions;
	}

3.1 非Component注解Bean读取

Spring除了用@Compoent及其子注解@Service等定义Bean之外,还可以在@Configuration注解的类中使用@Bean定义Bean,那么这些@Bean和@Component有什么区别呢?二者的读取方式不同,@Component是通过Spring容器启动的时候扫描包查找到的,而@Bean是Spring容器的初始化过程中,通过特定的BeanFactoryPostProcessor扫描@Bean注解,然后向容器中注册这些Bean定义。

3.2. 总结

通过以上步骤,Spring会扫描指定包下面的所有class文件,提取包含特定注解的class,然后解析为Spring的BeanDefinition。

我是御狐神,欢迎大家关注我的微信公众号
qrcode_for_gh_83670e17bbd7_344-2021-09-04-10-55-16

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

-御狐神-

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值