Spring IOC BeanDefinitions加载(一)

#博学谷IT学习技术支持#


今天我们来看一下beanDefinitions的解析加载操作

loadBeanDefinitions方法

protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException {
	Resource[] configResources = getConfigResources();
	if (configResources != null) {
		// 方法内部会遍历configResources,然后调用loadBeanDefinitions(Resource resource)方法
		reader.loadBeanDefinitions(configResources);
	}
	String[] configLocations = getConfigLocations();
	if (configLocations != null) {
		// 该方法内部会先根据location解析到相应的Resource资源,然后最终也会调用到loadBeanDefinitions(Resource resource)方法
		reader.loadBeanDefinitions(configLocations);
	}
}

getConfigResources和getConfigLocations方法都是获取具体的配置文件。不过getConfigResources()获取的是Resource类型,而getConfigLocations()获取的String类型的路径。

继续跟进,看reader.loadBeanDefinitions(configLocations)内容的处理逻辑

public int loadBeanDefinitions(String... locations) throws BeanDefinitionStoreException {
	Assert.notNull(locations, "Location array must not be null");
	int count = 0;
	for (String location : locations) {
		count += loadBeanDefinitions(location);
	}
	return count;
}

其实内部就是遍历locations,然后逐个进行解析加载操作;

继续跟进到下面的方法。该方法的主要作用就是将String类型的location地址加载为相应的Resource资源,然后调用loadBeanDefinitions(Resource resource)方法

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);
				int count = loadBeanDefinitions(resources);
				if (actualResources != null) {
					Collections.addAll(actualResources, resources);
				}
				if (logger.isTraceEnabled()) {
					logger.trace("Loaded " + count + " bean definitions from location pattern [" + location + "]");
				}
				return count;
			}
			catch (IOException ex) {
				throw new BeanDefinitionStoreException(
						"Could not resolve bean definition resource pattern [" + location + "]", ex);
			}
		}
		else {
			// Can only load single resources by absolute URL.
			Resource resource = resourceLoader.getResource(location);
			int count = loadBeanDefinitions(resource);
			if (actualResources != null) {
				actualResources.add(resource);
			}
			if (logger.isTraceEnabled()) {
				logger.trace("Loaded " + count + " bean definitions from location [" + location + "]");
			}
			return count;
		}
	}

继续跟进到 loadBeanDefinitions(EncodedResource encodedResource)方法
方法的核心逻辑主要下面这块。首先获取输入流,然后获取字符集,并封装为InputSource类型,作为参数传入doLoadBeanDefinition(InputSource inputSource, Resource resource)方法;

try (InputStream inputStream = encodedResource.getResource().getInputStream()) {
	InputSource inputSource = new InputSource(inputStream);
	if (encodedResource.getEncoding() != null) {
		inputSource.setEncoding(encodedResource.getEncoding());
	}
	return doLoadBeanDefinitions(inputSource, encodedResource.getResource());
}

doLoadBeanDefinitions

其实在doLoadBeanDefinitions方法之前的这些都只是准备操作。现在开始正式的解析操作

// 首先加载出Document
Document doc = doLoadDocument(inputSource, resource);
// 根据加载出的Document去解析加载并注册BeanDefinition
int count = registerBeanDefinitions(doc, resource);
if (logger.isDebugEnabled()) {
	logger.debug("Loaded " + count + " bean definitions from " + resource);
}
// 返回加载BeanDefintion的数量
return count;

第一步加载Document的操作这里就不看了,有兴趣的可以去看一下。
主要操作是registerBeanDefinitions(doc, resource);继续跟进看下;

registerBeanDefinitions

public int registerBeanDefinitions(Document doc, Resource resource) throws BeanDefinitionStoreException {
	// 创建BeanDefinitionDocumentReader 
	BeanDefinitionDocumentReader documentReader = createBeanDefinitionDocumentReader();
	// 获取加载注册前的BeanDefinition数量
	int countBefore = getRegistry().getBeanDefinitionCount();
	//将加载BeanDefinitions的工作交给BeanDefinitionDocumentReader,并封装一个XmlReaderContext对象
	documentReader.registerBeanDefinitions(doc, createReaderContext(resource));
	// 返回当前加载注册的BeanDefinition数量
	return getRegistry().getBeanDefinitionCount() - countBefore;
}

将具体的注册逻辑放到了BeanDefinitionDocumentReader 接口的实现类中,而具体的实现类是XmlBeanDefinitionReader类中的documentReaderClass 属性;
private Class<? extends BeanDefinitionDocumentReader> documentReaderClass = DefaultBeanDefinitionDocumentReader.class;

继续跟进到 DefaultBeanDefinitionDocumentReader.registerBeanDefinitions(Document doc, XmlReaderContext readerContext)方法

public void registerBeanDefinitions(Document doc, XmlReaderContext readerContext) {
	this.readerContext = readerContext;
	doRegisterBeanDefinitions(doc.getDocumentElement());
}

将readerContext赋值给this.readerContent属性,然后调用 doRegisterBeanDefinitions(doc.getDocumentElement())方法
看下doRegisterBeanDefinitions(Element root)内部逻辑

	protected void doRegisterBeanDefinitions(Element root) {
		BeanDefinitionParserDelegate parent = this.delegate;
		// 创建一个委托类,具体的默认命名空间的解析在委托类中进行
		this.delegate = createDelegate(getReaderContext(), root, parent);
		// 判断是否为默认的命名空间。默认的命名空间为 http://www.springframework.org/schema/beans
		if (this.delegate.isDefaultNamespace(root)) {
			//获取profile属性
			String profileSpec = root.getAttribute(PROFILE_ATTRIBUTE);
			if (StringUtils.hasText(profileSpec)) {
				String[] specifiedProfiles = StringUtils.tokenizeToStringArray(
						profileSpec, BeanDefinitionParserDelegate.MULTI_VALUE_ATTRIBUTE_DELIMITERS);
				if (!getReaderContext().getEnvironment().acceptsProfiles(specifiedProfiles)) {
					if (logger.isDebugEnabled()) {
						logger.debug("Skipped XML bean definition file due to specified profiles [" + profileSpec +
								"] not matching: " + getReaderContext().getResource());
					}
					return;
				}
			}
		}
		// 处理前置,由子类重载实现
		preProcessXml(root);
		// 具体的解析BeanDefinition的操作
		parseBeanDefinitions(root, this.delegate);
		// 处理后置,由子类重载实现
		postProcessXml(root);

		this.delegate = parent;
	}

跟进parseBeanDefinitions(Element root, BeanDefinitionParserDelegate delegate)

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

该方法开始进行BeanDefinition的解析注册操作,我们下一章继续

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值