一、开山篇

这个系列将会作为我阅读Spring相关书籍后的一些整理和学习到的内容所做一些分享,可能会有不对的地方。欢迎指正。

声明,我所导入的是Spring5.1.5版本。

二、从Bean的加载开始

BeanFactory bf = new XmlBeanFactory(new ClassPathResource("/*.xml"));

我们围绕这句代码展开。

1.对Resource接口有一个认识,它是Spring抽象的底层资源,例如File、URL、ClassPath等等。

其实我们现在可以理解为将配置文件转换成了一个Resource类。

接着向下分析XmlBeanFactory类的构造函数

public XmlBeanFactory(Resource resource) throws BeansException {
		this(resource, null);
	}

/*
其实调用的是这个构造函数
*/
public XmlBeanFactory(Resource resource, BeanFactory parentBeanFactory) throws BeansException {
		super(parentBeanFactory);//这个方法会忽略给定的依赖接口,不是我们分析的重点先略过。
		this.reader.loadBeanDefinitions(resource);
	}

this.reader.loadBeanDefinitions(resource); 

我们跟着这个方法追下去,它就是Spring加载Bean的入口。

@Override
	public int loadBeanDefinitions(Resource resource) throws BeanDefinitionStoreException {
		/*
            EncodedResource就是一个编码器会对给入的Resource进行编码 核心就是他的getReader()方法如果制定了编码格式就会进行编码。
        */
        return loadBeanDefinitions(new EncodedResource(resource));
	}

紧跟 loadBeanDefinitions(new EncodedResource(resource));

public int loadBeanDefinitions(EncodedResource encodedResource) throws BeanDefinitionStoreException {
		Assert.notNull(encodedResource, "EncodedResource must not be null");
		if (logger.isTraceEnabled()) {
			logger.trace("Loading XML bean definitions from " + encodedResource);
		}

		Set<EncodedResource> currentResources = this.resourcesCurrentlyBeingLoaded.get();
		if (currentResources == null) {
			currentResources = new HashSet<>(4);
			this.resourcesCurrentlyBeingLoaded.set(currentResources);
		}
		if (!currentResources.add(encodedResource)) {
			throw new BeanDefinitionStoreException(
					"Detected cyclic loading of " + encodedResource + " - check your import definitions!");
		}
		try {
			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();
			}
		}
	}

跟踪  doLoadBeanDefinitions(inputSource, encodedResource.getResource()); 

protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource)
			throws BeanDefinitionStoreException {

		try {
			Document doc = doLoadDocument(inputSource, resource);
			int count = registerBeanDefinitions(doc, resource);
			if (logger.isDebugEnabled()) {
				logger.debug("Loaded " + count + " bean definitions from " + resource);
			}
			return count;
		}
		catch (BeanDefinitionStoreException ex) {
			throw ex;
		}
		catch (SAXParseException ex) {
			throw new XmlBeanDefinitionStoreException(resource.getDescription(),
					"Line " + ex.getLineNumber() + " in XML document from " + resource + " is invalid", ex);
		}
		catch (SAXException ex) {
			throw new XmlBeanDefinitionStoreException(resource.getDescription(),
					"XML document from " + resource + " is invalid", ex);
		}
		catch (ParserConfigurationException ex) {
			throw new BeanDefinitionStoreException(resource.getDescription(),
					"Parser configuration exception parsing XML from " + resource, ex);
		}
		catch (IOException ex) {
			throw new BeanDefinitionStoreException(resource.getDescription(),
					"IOException parsing XML document from " + resource, ex);
		}
		catch (Throwable ex) {
			throw new BeanDefinitionStoreException(resource.getDescription(),
					"Unexpected exception parsing XML document from " + resource, ex);
		}
	}

除去对try,catch异常捕获的处理以外,这段代码其实就只在做两件事情:

1)Document doc = doLoadDocument(inputSource, res ource);

将XML加载成为Document对象,接下来的注册bean需要用到

2)int count = registerBeanDefinitions(doc, resource);

根据返回的Document对象注册Bean信息

注:可能由于版本的差异化,在前期的版本中会在加载Document对象之前再多出一步来。getValidationModeForResource(resource)

那我们就讲这个方法也讲述一下吧。

其实很简单就是校验我们XML文件的解析格式是DTD还是XSD,如何判断呢?其实DTD会有一个DOCTYPE的头而XSD没有,Sping就是这样一个校验规则。如果感兴趣可以选一个5.0的版本看一看。

接下来我们分析第一步,加载Document对象。

protected Document doLoadDocument(InputSource inputSource, Resource resource) throws Exception {
		return this.documentLoader.loadDocument(inputSource, getEntityResolver(), this.errorHandler,
				getValidationModeForResource(resource), isNamespaceAware());
	}

追踪下去就发现Document对象是一个接口,继而又委托给DocumentLoader,它也是个接口。其实方法的真正实现是DefaultDocumentLoader对象。

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

该方法内部其实很简单,就是有工厂类创造DocumentBuilder对象,最后再由parse方法返回Document对象。但是EntityResolver对象是什么?

其实它是SAX应用实现外部自定义处理类的时候就需要实现该接口,该接口内的方法就是resolveEntity(String publicId,String systemId)

publicId,在XSD模式下是null,在DTD模式下是有值的,例如:-//Spring//DTD BEAN 2.0//EN 其实就是URL后半部分

systemId就是头部引入的具体URL

那完成这一步之后还有一步就是对注册以及解析BeanDefinitions

public int registerBeanDefinitions(Document doc, Resource resource) throws BeanDefinitionStoreException {
		BeanDefinitionDocumentReader documentReader = createBeanDefinitionDocumentReader();
		int countBefore = getRegistry().getBeanDefinitionCount();
		documentReader.registerBeanDefinitions(doc, createReaderContext(resource));
		return getRegistry().getBeanDefinitionCount() - countBefore;
	}

向下追踪documentReader.registerBeanDefinitions(doc, createReaderContext(resource));

发现是接口,这个接口只有一个默认的实现就是DefaultBeanDefinitionDocumentReader

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

再追踪doRegisterBeanDefinitions(doc.getDocumentElement());

@SuppressWarnings("deprecation")  // for Environment.acceptsProfiles(String...)
	protected void doRegisterBeanDefinitions(Element root) {
		// Any nested <beans> elements will cause recursion in this method. In
		// order to propagate and preserve <beans> default-* attributes correctly,
		// keep track of the current (parent) delegate, which may be null. Create
		// the new (child) delegate with a reference to the parent for fallback purposes,
		// then ultimately reset this.delegate back to its original (parent) reference.
		// this behavior emulates a stack of delegates without actually necessitating one.
		BeanDefinitionParserDelegate parent = this.delegate;
		this.delegate = createDelegate(getReaderContext(), root, parent);

		if (this.delegate.isDefaultNamespace(root)) {
			String profileSpec = root.getAttribute(PROFILE_ATTRIBUTE);
			if (StringUtils.hasText(profileSpec)) {
				String[] specifiedProfiles = StringUtils.tokenizeToStringArray(
						profileSpec, BeanDefinitionParserDelegate.MULTI_VALUE_ATTRIBUTE_DELIMITERS);
				// We cannot use Profiles.of(...) since profile expressions are not supported
				// in XML config. See SPR-12458 for details.
				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);
		parseBeanDefinitions(root, this.delegate);
		postProcessXml(root);

		this.delegate = parent;
	}

最核心的就是

   preProcessXml(root);
    parseBeanDefinitions(root, this.delegate);
    postProcessXml(root);

除了parseBeanDefinitions(root, this.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);
		}
	}

以上的代码逻辑还是比较清晰,因为Spring就是两种Bean一种是默认的还有一个是自定义的。他就围绕这两种Bean展开注册和解析。那么如何判断呢,Spring的逻辑还是判断命名空间。关于自定义和默认标签我们下次再讲。

三、总结

ok,以上就是对Bean加载的初步学习,其实Bean到这里还没有进入内存只是变为一个BeanDefinition还有我们的标签的相关知识还没有提及到。如果有不足欢迎指正。