基于Xml 的IOC 容器-载入<bean>元素

Bean 配置信息中的<import>和<alias>元素解析在DefaultBeanDefinitionDocumentReader 中已经完成,对Bean 配置信息中使用最多的<bean>元素交由BeanDefinitionParserDelegate 来解析,其解析实现的源码如下:

//解析<Bean>元素的入口
@Nullable
public BeanDefinitionHolder parseBeanDefinitionElement(Element ele) {
	return parseBeanDefinitionElement(ele, null);
}

//解析Bean定义资源文件中的<Bean>元素,这个方法中主要处理<Bean>元素的id,name和别名属性
@Nullable
public BeanDefinitionHolder parseBeanDefinitionElement(Element ele, @Nullable BeanDefinition containingBean) {
	//获取<Bean>元素中的id属性值
	String id = ele.getAttribute(ID_ATTRIBUTE);
	//获取<Bean>元素中的name属性值
	String nameAttr = ele.getAttribute(NAME_ATTRIBUTE);

	//获取<Bean>元素中的alias属性值
	List<String> aliases = new ArrayList<>();

	//将<Bean>元素中的所有name属性值存放到别名中
	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");
		}
	}

	//检查<Bean>元素所配置的id或者name的唯一性,containingBean标识<Bean>
	//元素中是否包含子<Bean>元素
	if (containingBean == null) {
		//检查<Bean>元素所配置的id、name或者别名是否重复
		checkNameUniqueness(beanName, aliases, ele);
	}

	//详细对<Bean>元素中配置的Bean定义进行解析的地方
	AbstractBeanDefinition beanDefinition = parseBeanDefinitionElement(ele, beanName, containingBean);
	if (beanDefinition != null) {
		if (!StringUtils.hasText(beanName)) {
			try {
				if (containingBean != null) {
					//如果<Bean>元素中没有配置id、别名或者name,且没有包含子元素
					//<Bean>元素,为解析的Bean生成一个唯一beanName并注册
					beanName = BeanDefinitionReaderUtils.generateBeanName(
							beanDefinition, this.readerContext.getRegistry(), true);
				}
				else {
					//如果<Bean>元素中没有配置id、别名或者name,且包含了子元素
					//<Bean>元素,为解析的Bean使用别名向IOC容器注册
					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.
					//为解析的Bean使用别名注册时,为了向后兼容
					//Spring1.2/2.0,给别名添加类名后缀
					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);
	}
	//当解析出错时,返回null
	return null;
}

protected void checkNameUniqueness(String beanName, List<String> aliases, Element beanElement) {
	String foundName = null;

	if (StringUtils.hasText(beanName) && this.usedNames.contains(beanName)) {
		foundName = beanName;
	}
	if (foundName == null) {
		foundName = CollectionUtils.findFirstMatch(this.usedNames, aliases);
	}
	if (foundName != null) {
		error("Bean name '" + foundName + "' is already used in this <beans> element", beanElement);
	}

	this.usedNames.add(beanName);
	this.usedNames.addAll(aliases);
}

//详细对<Bean>元素中配置的Bean定义其他属性进行解析
//由于上面的方法中已经对Bean的id、name和别名等属性进行了处理
//该方法中主要处理除这三个以外的其他属性数据
@Nullable
public AbstractBeanDefinition parseBeanDefinitionElement(
		Element ele, String beanName, @Nullable BeanDefinition containingBean) {
	//记录解析的<Bean>
	this.parseState.push(new BeanEntry(beanName));

	//这里只读取<Bean>元素中配置的class名字,然后载入到BeanDefinition中去
	//只是记录配置的class名字,不做实例化,对象的实例化在依赖注入时完成
	String className = null;

	//如果<Bean>元素中配置了parent属性,则获取parent属性的值
	if (ele.hasAttribute(CLASS_ATTRIBUTE)) {
		className = ele.getAttribute(CLASS_ATTRIBUTE).trim();
	}
	String parent = null;
	if (ele.hasAttribute(PARENT_ATTRIBUTE)) {
		parent = ele.getAttribute(PARENT_ATTRIBUTE);
	}

	try {
		//根据<Bean>元素配置的class名称和parent属性值创建BeanDefinition
		//为载入Bean定义信息做准备
		AbstractBeanDefinition bd = createBeanDefinition(className, parent);

		//对当前的<Bean>元素中配置的一些属性进行解析和设置,如配置的单态(singleton)属性等
		parseBeanDefinitionAttributes(ele, beanName, containingBean, bd);
		//为<Bean>元素解析的Bean设置description信息
		bd.setDescription(DomUtils.getChildElementValueByTagName(ele, DESCRIPTION_ELEMENT));

		//对<Bean>元素的meta(元信息)属性解析
		parseMetaElements(ele, bd);
		//对<Bean>元素的lookup-method属性解析
		parseLookupOverrideSubElements(ele, bd.getMethodOverrides());
		//对<Bean>元素的replaced-method属性解析
		parseReplacedMethodSubElements(ele, bd.getMethodOverrides());

		//解析<Bean>元素的构造方法设置
		parseConstructorArgElements(ele, bd);
		//解析<Bean>元素的<property>设置
		parsePropertyElements(ele, bd);
		//解析<Bean>元素的qualifier属性
		parseQualifierElements(ele, bd);

		//为当前解析的Bean设置所需的资源和依赖对象
		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();
	}

	//解析<Bean>元素出错时,返回null
	return null;
}

只要使用过Spring,对Spring 配置文件比较熟悉的人,通过对上述源码的分析,就会明白我们在Spring配置文件中<Bean>元素的中配置的属性就是通过该方法解析和设置到Bean 中去的。

注意:在解析<Bean>元素过程中没有创建和实例化Bean 对象,只是创建了Bean 对象的定义类BeanDefinition,将<Bean>元素中的配置信息设置到BeanDefinition 中作为记录,当依赖注入时才使用这些记录信息创建和实例化具体的Bean 对象。

上面方法中一些对一些配置如元信息(meta)、qualifier 等的解析,我们在Spring 中配置时使用的也不多,我们在使用Spring 的<Bean>元素时,配置最多的是<property>属性,因此我们下面继续分析源码,了解Bean 的属性在解析时是如何设置的。

 

Python网络爬虫与推荐算法新闻推荐平台:网络爬虫:通过Python实现新浪新闻的爬取,可爬取新闻页面上的标题、文本、图片、视频链接(保留排版) 推荐算法:权重衰减+标签推荐+区域推荐+热点推荐.zip项目工程资源经过严格测试可直接运行成功且功能正常的情况才上传,可轻松复刻,拿到资料包后可轻松复现出一样的项目,本人系统开发经验充足(全领域),有任何使用问题欢迎随时与我联系,我会及时为您解惑,提供帮助。 【资源内容】:包含完整源码+工程文件+说明(如有)等。答辩评审平均分达到96分,放心下载使用!可轻松复现,设计报告也可借鉴此项目,该资源内项目代码都经过测试运行成功,功能ok的情况下才上传的。 【提供帮助】:有任何使用问题欢迎随时与我联系,我会及时解答解惑,提供帮助 【附带帮助】:若还需要相关开发工具、学习资料等,我会提供帮助,提供资料,鼓励学习进步 【项目价值】:可用在相关项目设计中,皆可应用在项目、毕业设计、课程设计、期末/期中/大作业、工程实训、大创等学科竞赛比赛、初期项目立项、学习/练手等方面,可借鉴此优质项目实现复刻,设计报告也可借鉴此项目,也可基于此项目来扩展开发出更多功能 下载后请首先打开README文件(如有),项目工程可直接复现复刻,如果基础还行,也可在此程序基础上进行修改,以实现其它功能。供开源学习/技术交流/学习参考,勿用于商业用途。质量优质,放心下载使用。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值