当前位置: 移动技术网 > IT编程>开发语言>Java > 荐 Spring源码之容器的基本实现:通过Xml配置装载Bean

荐 Spring源码之容器的基本实现:通过Xml配置装载Bean

2020年07月14日  | 移动技术网IT编程  | 我要评论

Spring通过Xml配置来装载Bean的的流程: 读取xml配置文件 》解析Xml并找到对应类的配置 》实例化对象

环境准备

这是一个简单的bean

public class User {
	private String name;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

}

这是一个简单的bean配置(web.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

	<bean id="user" class="com.example.bean.User"/>

</beans>

这是加载bean的示例代码:

public class TestBean {
	@Test
	public void testBean() {
		//创建默认bean工厂
		DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
		//创建bean定义读取器
		XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(factory);
		//获取资源
		ClassPathResource resource = new ClassPathResource("web.xml");
		//装载资源
		reader.loadBeanDefinitions(resource);
		//获取bean
		User user = factory.getBean("user", User.class);
		user.setName("小红");
		System.out.println(user.getName());
	}
}

Bean从何来
下面,我将按以下顺序介绍Spring是如何通过Xml配置装载Bean:

  • ClassPathResource
    对Xml配置文件进行封装
  • XmlBeanDefinitionReader
    把封装好的Xml(Resource)解析为BeanDefinition
  • DefaultListableBeanFactory
    -把BeanDefinition装载在进Bean工厂中

ClassPathResource

先看看类图:
在这里插入图片描述
再看看源码:


public ClassPathResource(String path) {
	this(path, (ClassLoader) null);
}

public ClassPathResource(String path, @Nullable ClassLoader classLoader) {
	Assert.notNull(path, "Path must not be null");
	String pathToUse = StringUtils.cleanPath(path);
	if (pathToUse.startsWith("/")) {
		pathToUse = pathToUse.substring(1);
	}
	this.path = pathToUse;
	this.classLoader = (classLoader != null ? classLoader : ClassUtils.getDefaultClassLoader());
}

Spring对Xml配置文件的封装,其实就是为了通过ClassPathResource得到java.io.InputStream。可以看到InputStreamSource里面只有一个方法。

public interface InputStreamSource {

	/**
	 * Return an {@link InputStream} for the content of an underlying resource.
	 * <p>It is expected that each call creates a <i>fresh</i> stream.
	 * <p>This requirement is particularly important when you consider an API such
	 * as JavaMail, which needs to be able to read the stream multiple times when
	 * creating mail attachments. For such a use case, it is <i>required</i>
	 * that each {@code getInputStream()} call returns a fresh stream.
	 * @return the input stream for the underlying resource (must not be {@code null})
	 * @throws java.io.FileNotFoundException if the underlying resource doesn't exist
	 * @throws IOException if the content stream could not be opened
	 */
	InputStream getInputStream() throws IOException;

}

Resoure则抽象出了Spring对资源对象操作的各种方法:

public interface Resource extends InputStreamSource {

	/**
	 * 确定资源是否存在
	 */
	boolean exists();

	/**
	 * 是否可读
	 */
	default boolean isReadable() {
		return exists();
	}

	/**
	 * 判断资源是否已经被打开
	 */
	default boolean isOpen() {
		return false;
	}

	/**
	 * 是否为文件
	 */
	default boolean isFile() {
		return false;
	}

	/**
	 * 返回此资源的URL
	 */
	URL getURL() throws IOException;

	/**
	 * 返回此资源的URI
	 */
	URI getURI() throws IOException;

	/**
	 * 把资源转换为File
	 */
	File getFile() throws IOException;

	/**
	 * 返回一个可以读取字节的通道
	 */
	default ReadableByteChannel readableChannel() throws IOException {
		return Channels.newChannel(getInputStream());
	}

	/**
	 * 确定此资源的内容长度
	 */
	long contentLength() throws IOException;

	/**
	 * 确定此资源的最后修改的时间戳
	 */
	long lastModified() throws IOException;

	/**
	 * 创建与此资源相关的资源
	 */
	Resource createRelative(String relativePath) throws IOException;

	/**
	 * 确定此资源的文件名,通常是路径的最后部分,比如 "myfile.txt"
	 */
	@Nullable
	String getFilename();

	/**
	 * 返回此资源的描述,用作使用该资源时的错误输出
	 */
	String getDescription();

}

对不同来源的资源文件都有相应的 Resource 实现,如 文件( FileSystemResource)、 Classpath 资源( ClassPathResource )、 URL 资源( UrlResource )、 InputStream 资源( InputStreamResource)、Byte 数组( ByteArrayResource )等。
在这里插入图片描述
在日常的开发中,也可以用到Spring这些类,比如,在加载ClassPath路径下的文件时,可以使用以下操作:

ClassPathResource resource = new ClassPathResource("web.xml");
InputStream inputStream = resource.getInputStream();

XmlBeanDefinitionReader

当通过Resource完成对Xml配置文件的封装后,文件的读取就交给XmlBeanDefinitionReader了。
在前面的代码中,reader.loadBeanDefinitions(resource),这个loadBeanDefinitions就是读取Xml。下面看看源码:

//进来就把Resource封装成EncodedResource,当设置了文件编码属性的时候 Spring会使用相应的编码作为输入流的编码
public int loadBeanDefinitions(Resource resource) throws BeanDefinitionStoreException {
	//以某种编码读取resource,默认不指定编码
	return loadBeanDefinitions(new EncodedResource(resource));
}


public int loadBeanDefinitions(EncodedResource encodedResource) throws BeanDefinitionStoreException {
	.......
	//ThreadLocal,保证加载资源时线程安全和高效
	Set<EncodedResource> currentResources = this.resourcesCurrentlyBeingLoaded.get();
	//添加source前判断是否已存在加载过的source,避免循环加载
	if (!currentResources.add(encodedResource)) {
		throw new BeanDefinitionStoreException(
				"Detected cyclic loading of " + encodedResource + " - check your import definitions!");
	}
	//从EncodedResource中获取对应的 InputStream 并构造 InputSource
	try (InputStream inputStream = encodedResource.getResource().getInputStream()) {
		InputSource inputSource = new InputSource(inputStream);
		if (encodedResource.getEncoding() != null) {
			inputSource.setEncoding(encodedResource.getEncoding());
		}
		//在Spring里面,do方法才是真正干活的
		return doLoadBeanDefinitions(inputSource, encodedResource.getResource());
	}
	......
	finally {
		currentResources.remove(encodedResource);
		if (currentResources.isEmpty()) {
			//使用ThreadLocal后及时调用remove方法,防止内存泄漏
			this.resourcesCurrentlyBeingLoaded.remove();
		}
	}
}

而在方法中,就做了两件事:

protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource)
		throws BeanDefinitionStoreException {
	try {
		//把source封装成Document
		Document doc = doLoadDocument(inputSource, resource);
		//根据Document注册bean信息
		int count = registerBeanDefinitions(doc, resource);
		if (logger.isDebugEnabled()) {
			logger.debug("Loaded " + count + " bean definitions from " + resource);
		}
		return count;
	}
	catch (BeanDefinitionStoreException ex) {

下面我们来详细看看这两件事具体是怎么做的:

  1. 首先,doLoadDocument方法把source封装成了Document。
protected Document doLoadDocument(InputSource inputSource, Resource resource) throws Exception {
	return this.documentLoader.loadDocument(inputSource, getEntityResolver(), this.errorHandler,
			getValidationModeForResource(resource), isNamespaceAware());
}

这里面有两个方法需要说明一下:

  • getEntityResolver
    Spring是使用SAX解析XML文档的,在解析XML文档时,SAX首先读取该XML档上的声明,根据声明去寻找相应的DTD定义,以便对文档进行一个验证。默认的寻找规则,就是通过网络(实现上就是声明的DTD URI地址)来下载相应的DTD声明,并进行认证。而下载的过程是一个漫长的过程,而且当网络中断或不可用时,这里会报错,就是因为相应的DTD声明没有被找到的原。而getEntityResolver方法的作用是项目本身就可以提供一个如何寻找DTD声明的方法,比如我们将DTD文件放到项目中某处,在实现时直接将此文档读取并返回给SAX即可,这样就避免了通过网络来找相应的声明。默认情况下,Spring的DTD文件放在此路径: /org/springframework/beans/factory/xml/,Spring会首先从这个目录去获取规范文件,如果找不到去项目路径下载找,再找不到就通过网络下载。
  • getValidationModeForResource
    用来判断xml文件使用DTD模式还是XSD模式校验。先判断使用功能什么验证模式,如果手动指定了验证模式则使用指定的验证模式,如果未指定则使用自动检测,自动检测其实就是判断文件是否具有{DOCTYPE} 定义,有则使用DTD验证,无则采用XSD验证。

至于loadDocument就是普通的SAX解析 XML文档的套路:通过factory创建builder,再通过builder解析source获取document。

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);
}
  1. 然后,registerBeanDefinitions才是提取和注册bean的地方。点进去可以发现实际调用的是DefaultBeanDefinitionDocumentReader里面的方法:
public void registerBeanDefinitions(Document doc, XmlReaderContext readerContext) {
	this.readerContext = readerContext;
	doRegisterBeanDefinitions(doc.getDocumentElement());
}

/**
 * 在给定的根{@code <beans />}元素中注册每个bean定义。
 * 任何嵌套的<beans>元素都将导致此方法中的递归
 */
protected void doRegisterBeanDefinitions(Element root) {
	BeanDefinitionParserDelegate parent = this.delegate;
	this.delegate = createDelegate(getReaderContext(), root, parent);

	if (this.delegate.isDefaultNamespace(root)) {
		//处理profile属性,profile=("dev",""test,"prod"),用来区分开发、测试和生产环境的配置:<beans profile="dev"></beans>
		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);
	parseBeanDefinitions(root, this.delegate);
	//解析后处理(空方法,留给子类实现)
	postProcessXml(root);

	this.delegate = parent;
}

//解析并注册bean
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;
				//解析默认bean配置,如<bean id="test" class="test.TestBean" />
				if (delegate.isDefaultNamespace(ele)) {
					parseDefaultElement(ele, delegate);
				}
				//解析自定义配置,如<tx :annotation-driven/>
				else {
					delegate.parseCustomElement(ele);
				}
			}
		}
	}
	else {
		delegate.parseCustomElement(root);
	}
}

至于详细的解析bean标签的过程,请看下回分解。。。

本文地址:https://blog.csdn.net/u013998466/article/details/107004862

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网