spring源码(三)- (obtainFreshBeanFactory)XML文件加载成BeanDefinition的过程及实现简单自定义标签

XML文件加载成BeanDefinition过程图解

03.xml文件加载成beanDefinition过程

obtainFreshBeanFactory

该方法的主要作用是将bean定义beandefinition加载到BeanFactory中。

  1. 该方法会解析所有 Spring 配置文件(application-**.xml),将所有 Spring 配置文件中的 bean 定义封装成 BeanDefinition,加载到 BeanFactory 中。
  2. 常见的,如果解析到<context:component-scan base-package="" /> 注解时,会扫描 base-package 指定的目录,将该目录下使用指定注解(@Controller、@Service、@Component、@Repository)的配置也同样封装成 BeanDefinition,加载到 BeanFactory 中。

三个重要的缓存

  • beanDefinitionNames缓存:所有被加载到 BeanFactory 中的bean的beanName 集合。
  • beanDefinitionMap缓存:所有被加载到 BeanFactory 中的bean的beanName和 BeanDefinition 映射。
  • aliasMap缓存:所有被加载到 BeanFactory 中的bean的beanName和别名映射。

加载过程的主要方法

loadBeanDefinitions(beanFactory)

loadBeanDefinitions 主要是创建beanDefinitionReader,同时调用loadBeanDefinitions(beanDefinitionReader)开始加载相关的配置文件

protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
   // Create a new XmlBeanDefinitionReader for the given BeanFactory.
   //创建一个XmlBeanDefinitionReader对象,并通过回调设置到BeanFactory中
   XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);

   // Configure the bean definition reader with this context's
   // resource loading environment.
   //给Reader对象设置环境对象
   beanDefinitionReader.setEnvironment(this.getEnvironment());
   beanDefinitionReader.setResourceLoader(this);
   beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));

   // Allow a subclass to provide custom initialization of the reader,
   // then proceed with actually loading the bean definitions.
   //初始化beanDefinitionReader对象,此处设置配置文件是否要进行验证(适配器模式)
   initBeanDefinitionReader(beanDefinitionReader);
   //开始完成beanDefinition的加载
   loadBeanDefinitions(beanDefinitionReader);
}

loadBeanDefinitions系列方法

loadBeanDefinitions的 一系列重载方法,string[]->string->resource[]->resource,最终调用doLoadBeanDefinitions进行核心处理单个资源,解析相关文件

protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException {
   //以Resource的方式获取配置文件的资源位置
   Resource[] configResources = getConfigResources();
   if (configResources != null) {
      reader.loadBeanDefinitions(configResources);
   }
   //以String的方式获取配置文件的资源位置
   String[] configLocations = getConfigLocations();
   if (configLocations != null) {
      reader.loadBeanDefinitions(configLocations);
  }
}
====================================
    //将string[]通过遍历解析
	@Override
	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;
	}

=================================
    //解析单个string的资源
	@Override
	public int loadBeanDefinitions(String location) throws BeanDefinitionStoreException {
		return loadBeanDefinitions(location, null);
	}
=================================
    //将单个string资源解析成resources[]
   	public int loadBeanDefinitions(String location, @Nullable Set<Resource> actualResources) throws BeanDefinitionStoreException {
		//获取ResourceLoader对象
		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 {
				//调用DefaultResourceLoader的getResource完成具体的Resource定位
				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;
		}
	}
=================================
    //解析resources[]数组资源
    	@Override
	public int loadBeanDefinitions(Resource... resources) throws BeanDefinitionStoreException {
		Assert.notNull(resources, "Resource array must not be null");
		int count = 0;
		for (Resource resource : resources) {
			count += loadBeanDefinitions(resource);
		}
		return count;
	}
=================================
    //解析resource资源
    	@Override
	public int loadBeanDefinitions(Resource resource) throws BeanDefinitionStoreException {
		return loadBeanDefinitions(new EncodedResource(resource));
	}
=================================
// 解析resource资源,同时来时进行处理核心步骤doLoadBeanDefinitions
	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.add(encodedResource)) {
			throw new BeanDefinitionStoreException(
					"Detected cyclic loading of " + encodedResource + " - check your import definitions!");
		}
		//从encodedResource中获取已经封装的Resource对象并再次从Resource中获取其中的InputStream
		try (InputStream inputStream = encodedResource.getResource().getInputStream()) {
			InputSource inputSource = new InputSource(inputStream);
			if (encodedResource.getEncoding() != null) {
				inputSource.setEncoding(encodedResource.getEncoding());
			}
			//逻辑处理的核心步骤
			return doLoadBeanDefinitions(inputSource, encodedResource.getResource());
		}
		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方法

doLoadBeanDefinitions主要是将resource读取成document文件,通过registerBeanDefinitions方法将文档中的相关标签解析成BeanDefinition

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

   try {
      //从此处获取XML文件中的Document对象,这个解析过程是有documentLoader完成
      /*解析的过程
      * 从String[]---String---Resource[]----resource,最终开始讲resource读取成一个document文档,
      * 根据文档的节点信息封装成一个个的BeanDefinition的对象
       *
      * */
      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);
   }
}

registerBeanDefinitions

registerBeanDefinitions主要是将Document和resource资源进行解析,调用doRegisterBeanDefinitions(doc.getDocumentElement())注册相关BeanDefinition,doRegisterBeanDefinitions才是真正干活的方法

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

doRegisterBeanDefinitions

doRegisterBeanDefinitions主要是最相关数据进行包装,主要是调用parseBeanDefinitions(root, this.delegate);进行bean的解析注册工作

	protected void doRegisterBeanDefinitions(Element root) {
		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);
				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;
	}

parseBeanDefinitions

在此处进行默认命名空间和自定义空间中的相关标签解析,默认的命名空间只有http://www.springframework.org/schema/beans,其余均为自定义命名空间

在解析相关标签的时候,会判断是否要完成spring内部的bean的加载过程

大部分inter的processer和注解相关,此处暂时不做说明

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;
            /*
             * 判断是否为默认的命名空间(可自定义命名空间)
             * 只是spring中的默认空间spring-bean等,不包含sprig-context等
             */
            if (delegate.isDefaultNamespace(ele)) {
               parseDefaultElement(ele, delegate);
            }
            else {
               /*
                * 对自定义默认空间进行解析
                * 如spring-context,spring-mvc等
                * 此处提供给其他地方进行拓展工作
                * */
               delegate.parseCustomElement(ele);
            }
         }
      }
   }
   else {
      delegate.parseCustomElement(root);
   }
}

默认命名空间标签解析

/**
 * 此方法对spring的默认命名空间中相关数据标签进行解析工作 ,四种不同标签解析逻辑不同
 * @param ele
 * @param delegate
 */
private void parseDefaultElement(Element ele, BeanDefinitionParserDelegate delegate) {
   if (delegate.nodeNameEquals(ele, IMPORT_ELEMENT)) {
      importBeanDefinitionResource(ele);
   }
   else if (delegate.nodeNameEquals(ele, ALIAS_ELEMENT)) {
      processAliasRegistration(ele);
   }
   else if (delegate.nodeNameEquals(ele, BEAN_ELEMENT)) {
      //对bean进行相关解析
      processBeanDefinition(ele, delegate);
   }
   else if (delegate.nodeNameEquals(ele, NESTED_BEANS_ELEMENT)) {
      // recurse
      doRegisterBeanDefinitions(ele);
   }
}

自定义命名空间标签解析

parseCustomElement最终会调用parse进行获取到的自定义标签进行解析,最终会将获取到的BeanDefinition通过registerBeanDefinition注册到beanDefinitionMap和beanDefinitionNames集合中

	public BeanDefinition parseCustomElement(Element ele, @Nullable BeanDefinition containingBd) {
		//获取对应标签的命名空间
		String namespaceUri = getNamespaceURI(ele);
		if (namespaceUri == null) {
			return null;
		}
		//根据命名空间找到对应的NamespaceHandler(spring.handler中)
		NamespaceHandler handler = this.readerContext.getNamespaceHandlerResolver().resolve(namespaceUri);
		if (handler == null) {
			error("Unable to locate Spring NamespaceHandler for XML schema namespace [" + namespaceUri + "]", ele);
			return null;
		}
		//调用自定义的NamespaceHandler进行解析
		return handler.parse(ele, new ParserContext(this.readerContext, this, containingBd));
	}

​ NamespaceHandler handler = this.readerContext.getNamespaceHandlerResolver().resolve(namespaceUri);中 resolve方法会获取springs.handler中的url 获取到对应的handeler

public class ContextNamespaceHandler extends NamespaceHandlerSupport {

	@Override
	public void init() {
		registerBeanDefinitionParser("property-placeholder", new PropertyPlaceholderBeanDefinitionParser());
		registerBeanDefinitionParser("property-override", new PropertyOverrideBeanDefinitionParser());
		registerBeanDefinitionParser("annotation-config", new AnnotationConfigBeanDefinitionParser());
		registerBeanDefinitionParser("component-scan", new ComponentScanBeanDefinitionParser());
		registerBeanDefinitionParser("load-time-weaver", new LoadTimeWeaverBeanDefinitionParser());
		registerBeanDefinitionParser("spring-configured", new SpringConfiguredBeanDefinitionParser());
		registerBeanDefinitionParser("mbean-export", new MBeanExportBeanDefinitionParser());
		registerBeanDefinitionParser("mbean-server", new MBeanServerBeanDefinitionParser());
	}

}

image-20210907165042959

image-20210907164643593

public final BeanDefinition parse(Element element, ParserContext parserContext) {
   AbstractBeanDefinition definition = parseInternal(element, parserContext);
   if (definition != null && !parserContext.isNested()) {
      try {
         String id = resolveId(element, definition, parserContext);
         if (!StringUtils.hasText(id)) {
            parserContext.getReaderContext().error(
                  "Id is required for element '" + parserContext.getDelegate().getLocalName(element)
                        + "' when used as a top-level tag", element);
         }
         String[] aliases = null;
         if (shouldParseNameAsAliases()) {
            String name = element.getAttribute(NAME_ATTRIBUTE);
            if (StringUtils.hasLength(name)) {
               aliases = StringUtils.trimArrayElements(StringUtils.commaDelimitedListToStringArray(name));
            }
         }
         // 将AbstractBeanDefinition转换为BeanDefinitionHolder并注册
         BeanDefinitionHolder holder = new BeanDefinitionHolder(definition, id, aliases);
         registerBeanDefinition(holder, parserContext.getRegistry());
         if (shouldFireEvents()) {
            // 通知监听器进行处理
            BeanComponentDefinition componentDefinition = new BeanComponentDefinition(holder);
            postProcessComponentDefinition(componentDefinition);
            parserContext.registerComponent(componentDefinition);
         }
      }
      catch (BeanDefinitionStoreException ex) {
         String msg = ex.getMessage();
         parserContext.getReaderContext().error((msg != null ? msg : ex.toString()), element);
         return null;
      }
   }
   return definition;
}

实现自定义标签

  1. 创建自定义parser

  2. 创建自定义的handeler

  3. 创建实体接收数据

  4. 在resource中创建META-INF(必须一样)目录,创建spring.handlers,spring.schemas,user.xsd三个文件(前两个文件名必须一样)

文件名必须一样的原因是在spring源码中这些路径和文件名是写死的,必须读取相关文件

用spring.handlers文件名时gradle会提示assert shortName != key错误 可以使用Spring.handlers文件名 或者屏蔽gradle/docs.gradle相关代码

UserBeanDefinitionParser

public class UserBeanDefinitionParser extends AbstractSingleBeanDefinitionParser {
	/**
	 *  返回属性值对应的对象
	 * @param element the {@code Element} that is being parsed
	 * @return
	 */
	@Override
	protected Class<?> getBeanClass(Element element) {
		return User.class;
	}

	@Override
	protected void doParse(Element element, BeanDefinitionBuilder builder) {
		// 获取标签具体的属性值
		String userName = element.getAttribute("userName");
		String email = element.getAttribute("email");
		String password = element.getAttribute("password");

		if(StringUtils.hasText(userName)){
			builder.addPropertyValue("username",userName);
		}
		if (StringUtils.hasText(email)){
			builder.addPropertyValue("email",email);
		}
		if (StringUtils.hasText(password)){
			builder.addPropertyValue("password",password);
		}
	}
}

UserNamespaceHandler

public class UserNamespaceHandler extends NamespaceHandlerSupport {
	@Override
	public void init() {
		registerBeanDefinitionParser("user", new UserBeanDefinitionParser());
	}
}

User

public class User {
	private String username;
	private String email;
	private String password;

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	@Override
	public String toString() {
		return "User{" +
				"username='" + username + '\'' +
				", email='" + email + '\'' +
				", password='" + password + '\'' +
				'}';
	}
}

spring.handlers

http\://doc.cnrfwang.top/schema/user=com.king.selfTag.UserNamespaceHandler

spring.schemas

http\://doc.cnrfwang.top/schema/user=com.king.selfTag.UserNamespaceHandler

user.xsd

<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema"
		targetNamespace="http://doc.cnrfwang.top/schema/user"
		elementFormDefault="qualified">
	<element name="user">
		<complexType>
			<attribute name ="id" type = "string"/>
			<attribute name ="userName" type = "string"/>
			<attribute name ="email" type = "string"/>
			<attribute name ="password" type="string"/>
		</complexType>
	</element>
</schema>

xml文件

aaa:user 中aaa必须和前面 xmlns:aaa 相同(通过aaa找到user的handeler),可以随便定义(不和原来已有相同即可)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	   xmlns:aaa="http://doc.cnrfwang.top/schema/user"
	   xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       http://doc.cnrfwang.top/schema/user http://doc.cnrfwang.top/schema/user.xsd">
	<aaa:user id = "wmx" userName = "lee" email = "bbb"/>
</beans>
posted @ 2021-09-07 17:28  知白守黑,和光同尘  阅读(88)  评论(0编辑  收藏  举报