Spring——简单介绍解析xml文件

本文主要介绍xml被解析到IOC容器中的过程

主要分为四步

  1. io流读取xml文件,生成InputSource对象
  2. documentLoader读取InputSource对象,转为Document
  3. NamespaceHandle解析Document成BeanDefinition
  4. 将beanDefinition放到容器中(beanDefinitionMap和beanDefinitionNames)

下面把部分代码(核心代码)贴出来

第一步 (XmlBeanDefinitionReader类下的loadBeanDefinitions方法)
public int loadBeanDefinitions(EncodedResource encodedResource) throws BeanDefinitionStoreException {
		
		try (InputStream inputStream = encodedResource.getResource().getInputStream()) {
			InputSource inputSource = new InputSource(inputStream);
			if (encodedResource.getEncoding() != null) {
				inputSource.setEncoding(encodedResource.getEncoding());
			}
			return doLoadBeanDefinitions(inputSource, encodedResource.getResource());
		}
}
第二步 (XmlBeanDefinitionReader类下的doLoadBeanDefinitions方法)
protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource)
			throws BeanDefinitionStoreException {

		try {
			Document doc = doLoadDocument(inputSource, resource);
			int count = registerBeanDefinitions(doc, resource);
			return count;
		}
		
}
第三步(BeanDefinitionParserDelegate类型下的decorateIfRequired方法)
public BeanDefinitionHolder decorateIfRequired(
			Node node, BeanDefinitionHolder originalDef, @Nullable BeanDefinition containingBd) {
		String namespaceUri = getNamespaceURI(node);
		if (namespaceUri != null && !isDefaultNamespace(namespaceUri)) {
			NamespaceHandler handler = this.readerContext.getNamespaceHandlerResolver().resolve(namespaceUri);
			if (handler != null) {
				BeanDefinitionHolder decorated =
						handler.decorate(node, originalDef, new ParserContext(this.readerContext, this, containingBd));
				if (decorated != null) {
					return decorated;
				}
			}

		return originalDef;
	}

第四步 (DefaultListableBeanFactory类下的registerBeanDefinition)

@Override
	public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition)
			throws BeanDefinitionStoreException {


		BeanDefinition existingDefinition = this.beanDefinitionMap.get(beanName);
		
		// Still in startup registration phase
		this.beanDefinitionMap.put(beanName, beanDefinition);
		this.beanDefinitionNames.add(beanName);
		removeManualSingletonName(beanName);

	}




知是行之始,行是知之成!

你可能感兴趣的:(Spring相关,xml,spring,java)