Spring源码-解析xml文件自定义标签

一、NamespaceHandlerResolver的创建

    public int registerBeanDefinitions(Document doc, Resource resource) throws BeanDefinitionStoreException {
	// 对xml的beanDefinition进行解析
	BeanDefinitionDocumentReader documentReader = createBeanDefinitionDocumentReader();
	int countBefore = getRegistry().getBeanDefinitionCount();
	// 完成具体的解析过程
	documentReader.registerBeanDefinitions(doc, createReaderContext(resource));
	return getRegistry().getBeanDefinitionCount() - countBefore;
}


    public XmlReaderContext createReaderContext(Resource resource) {
	return new XmlReaderContext(resource, this.problemReporter, this.eventListener,
			this.sourceExtractor, this, getNamespaceHandlerResolver());
}


    public NamespaceHandlerResolver getNamespaceHandlerResolver() {
	if (this.namespaceHandlerResolver == null) {
		this.namespaceHandlerResolver = createDefaultNamespaceHandlerResolver();
	}
	return this.namespaceHandlerResolver;
}

    protected NamespaceHandlerResolver createDefaultNamespaceHandlerResolver() {
	ClassLoader cl = (getResourceLoader() != null ? getResourceLoader().getClassLoader() : getBeanClassLoader());
	return new DefaultNamespaceHandlerResolver(cl);
}

    public DefaultNamespaceHandlerResolver(@Nullable ClassLoader classLoader) {
	this(classLoader, DEFAULT_HANDLER_MAPPINGS_LOCATION); // public static final String DEFAULT_HANDLER_MAPPINGS_LOCATION = "META-INF/spring.handlers";
}

二、解析自定义标签

    @Nullable
public BeanDefinition parseCustomElement(Element ele) {
	return parseCustomElement(ele, null);
}

    	@Nullable
public BeanDefinition parseCustomElement(Element ele, @Nullable BeanDefinition containingBd) {
	// 获取对应的命名空间
	String namespaceUri = getNamespaceURI(ele);
	if (namespaceUri == null) {
		return null;
	}
	// 根据命名空间找到对应的NamespaceHandler
	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));
}

    @Override
@Nullable
public NamespaceHandler resolve(String namespaceUri) {
	// 获取所有已经配置好的handler映射
	Map<String, Object> handlerMappings = getHandlerMappings();
	// 根据命名空间找到对应的信息
	Object handlerOrClassName = handlerMappings.get(namespaceUri);
	if (handlerOrClassName == null) {
		return null;
	}
	else if (handlerOrClassName instanceof NamespaceHandler) {
		// 如果已经做过解析,直接从缓存中读取
		return (NamespaceHandler) handlerOrClassName;
	}
	else {
		// 没有做过解析,则返回的是类路径
		String className = (String) handlerOrClassName;
		try {
			// 通过反射将类路径转化为类
			Class<?> handlerClass = ClassUtils.forName(className, this.classLoader);
			if (!NamespaceHandler.class.isAssignableFrom(handlerClass)) {
				throw new FatalBeanException("Class [" + className + "] for namespace [" + namespaceUri +
						"] does not implement the [" + NamespaceHandler.class.getName() + "] interface");
			}
			// 实例化类
			NamespaceHandler namespaceHandler = (NamespaceHandler) BeanUtils.instantiateClass(handlerClass);
			// 调用自定义的namespaceHandler的初始化方法
                            /**
                             *以ContextNamespaceHandler为例
                              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());
                              	}
                              }
                            */
			namespaceHandler.init();
			// 讲结果记录在缓存中
			handlerMappings.put(namespaceUri, namespaceHandler);
			return namespaceHandler;
		}
		catch (ClassNotFoundException ex) {
			throw new FatalBeanException("Could not find NamespaceHandler class [" + className +
					"] for namespace [" + namespaceUri + "]", ex);
		}
		catch (LinkageError err) {
			throw new FatalBeanException("Unresolvable class definition for NamespaceHandler class [" +
					className + "] for namespace [" + namespaceUri + "]", err);
		}
	}
}

    /**
     *从META-INF/Spring.handlers下加载配置到handlerMappings 

    */
    private Map<String, Object> getHandlerMappings() {
	Map<String, Object> handlerMappings = this.handlerMappings;
	// 如果没有被缓存,则开始进行缓存
	if (handlerMappings == null) {
		synchronized (this) {
			handlerMappings = this.handlerMappings;
			if (handlerMappings == null) {
				if (logger.isTraceEnabled()) {
					logger.trace("Loading NamespaceHandler mappings from [" + this.handlerMappingsLocation + "]");
				}
				try {
					// this.handlerMappingsLocation在构造函数中已经被初始化为META-INF/Spring.handlers
					Properties mappings =
							PropertiesLoaderUtils.loadAllProperties(this.handlerMappingsLocation, this.classLoader);
					if (logger.isTraceEnabled()) {
						logger.trace("Loaded NamespaceHandler mappings: " + mappings);
					}
					handlerMappings = new ConcurrentHashMap<>(mappings.size());
					// 将properties格式文件合并到map格式的handlerMapping中
					CollectionUtils.mergePropertiesIntoMap(mappings, handlerMappings);
					this.handlerMappings = handlerMappings;
				}
				catch (IOException ex) {
					throw new IllegalStateException(
							"Unable to load NamespaceHandler mappings from location [" + this.handlerMappingsLocation + "]", ex);
				}
			}
		}
	}
	return handlerMappings;
}

以spring-context模块下的spring.handlers文件为例:

    http\://www.springframework.org/schema/context=org.springframework.context.config.ContextNamespaceHandler
    http\://www.springframework.org/schema/jee=org.springframework.ejb.config.JeeNamespaceHandler
    http\://www.springframework.org/schema/lang=org.springframework.scripting.config.LangNamespaceHandler
    http\://www.springframework.org/schema/task=org.springframework.scheduling.config.TaskNamespaceHandler
    http\://www.springframework.org/schema/cache=org.springframework.cache.config.CacheNamespaceHandler

调用自定义的NamespaceHandler进行解析

    @Override
@Nullable
public BeanDefinition parse(Element element, ParserContext parserContext) {
	// 获取元素的解析器
	BeanDefinitionParser parser = findParserForElement(element, parserContext);
	return (parser != null ? parser.parse(element, parserContext) : null);
}

   @Nullable
private BeanDefinitionParser findParserForElement(Element element, ParserContext parserContext) {
	// 获取元素名称
	String localName = parserContext.getDelegate().getLocalName(element);
	// 根据元素名称找到对应的解析器
	BeanDefinitionParser parser = this.parsers.get(localName);
	if (parser == null) {
		parserContext.getReaderContext().fatal(
				"Cannot locate BeanDefinitionParser for element [" + localName + "]", element);
	}
	return parser;
}

下面以context下的property-placeholder为例,property-placeholder对应的BeanDefinitionParser为PropertyPlaceholderBeanDefinitionParser:

类AbstractBeanDefinitionParser:

    @Override
@Nullable
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); // 解析id属性
			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); // 解析name属性
				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;
}

将element和parserContext解析成BeanDefinition,解析id和name属性并注册到beanFactory。

类AbstractSingleBeanDefinitionParser:

    @Override
protected final AbstractBeanDefinition parseInternal(Element element, ParserContext parserContext) {
	BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition();
	String parentName = getParentName(element);
	if (parentName != null) {
		builder.getRawBeanDefinition().setParentName(parentName);
	}
	// 获取自定义标签中的class,此时会调用自定义解析器
	Class<?> beanClass = getBeanClass(element);
	if (beanClass != null) {
		builder.getRawBeanDefinition().setBeanClass(beanClass);
	}
	else {
		// 若子类没有重写getBeanClass方法则尝试检查子类是否重写getBeanClassName方法
		String beanClassName = getBeanClassName(element);
		if (beanClassName != null) {
			builder.getRawBeanDefinition().setBeanClassName(beanClassName);
		}
	}
	builder.getRawBeanDefinition().setSource(parserContext.extractSource(element));
	BeanDefinition containingBd = parserContext.getContainingBeanDefinition();
	if (containingBd != null) {
		// Inner bean definition must receive same scope as containing bean.
		// 若存在父类则使用父类的scope属性
		builder.setScope(containingBd.getScope());
	}
	if (parserContext.isDefaultLazyInit()) {
		// Default-lazy-init applies to custom bean definitions as well.
		// 配置延迟加载
		builder.setLazyInit(true);
	}
	// 调用子类重写的doParse方法进行解析
	doParse(element, parserContext, builder);
	return builder.getBeanDefinition();
}

将element和parserContext解析成BeanDefinition,并可能设置parentName,beanClassName ,beanClass ,Scope,LazyInit等属性,调用doParse方法。BeanDefinition通过子类的getBeanClass或者getBeanClassName设置。

类AbstractPropertyLoadingBeanDefinitionParser:

    @Override
protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {
	String location = element.getAttribute("location");
	if (StringUtils.hasLength(location)) {
		location = parserContext.getReaderContext().getEnvironment().resolvePlaceholders(location);
		String[] locations = StringUtils.commaDelimitedListToStringArray(location);
		builder.addPropertyValue("locations", locations);
	}

	String propertiesRef = element.getAttribute("properties-ref");
	if (StringUtils.hasLength(propertiesRef)) {
		builder.addPropertyReference("properties", propertiesRef);
	}

	String fileEncoding = element.getAttribute("file-encoding");
	if (StringUtils.hasLength(fileEncoding)) {
		builder.addPropertyValue("fileEncoding", fileEncoding);
	}

	String order = element.getAttribute("order");
	if (StringUtils.hasLength(order)) {
		builder.addPropertyValue("order", Integer.valueOf(order));
	}

	builder.addPropertyValue("ignoreResourceNotFound",
			Boolean.valueOf(element.getAttribute("ignore-resource-not-found")));

	builder.addPropertyValue("localOverride",
			Boolean.valueOf(element.getAttribute("local-override")));

	builder.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
}

解析相应属性并设置到BeanDefinitionBuilder中

类PropertyPlaceholderBeanDefinitionParser:

    protected Class<?> getBeanClass(Element element) {
	// As of Spring 3.1, the default value of system-properties-mode has changed from
	// 'FALLBACK' to 'ENVIRONMENT'. This latter value indicates that resolution of
	// placeholders against system properties is a function of the Environment and
	// its current set of PropertySources.
	if (SYSTEM_PROPERTIES_MODE_DEFAULT.equals(element.getAttribute(SYSTEM_PROPERTIES_MODE_ATTRIBUTE))) {
		return PropertySourcesPlaceholderConfigurer.class;
	}

	// The user has explicitly specified a value for system-properties-mode: revert to
	// PropertyPlaceholderConfigurer to ensure backward compatibility with 3.0 and earlier.
	// This is deprecated; to be removed along with PropertyPlaceholderConfigurer itself.
	return org.springframework.beans.factory.config.PropertyPlaceholderConfigurer.class;
}


    @Override
protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {
	super.doParse(element, parserContext, builder); // 调用父类方法解析相应属性

	builder.addPropertyValue("ignoreUnresolvablePlaceholders",
			Boolean.valueOf(element.getAttribute("ignore-unresolvable")));

	String systemPropertiesModeName = element.getAttribute(SYSTEM_PROPERTIES_MODE_ATTRIBUTE);
	if (StringUtils.hasLength(systemPropertiesModeName) &&
			!systemPropertiesModeName.equals(SYSTEM_PROPERTIES_MODE_DEFAULT)) {
		builder.addPropertyValue("systemPropertiesModeName", "SYSTEM_PROPERTIES_MODE_" + systemPropertiesModeName);
	}

	if (element.hasAttribute("value-separator")) {
		builder.addPropertyValue("valueSeparator", element.getAttribute("value-separator"));
	}
	if (element.hasAttribute("trim-values")) {
		builder.addPropertyValue("trimValues", element.getAttribute("trim-values"));
	}
	if (element.hasAttribute("null-value")) {
		builder.addPropertyValue("nullValue", element.getAttribute("null-value"));
	}
}

解析属性

posted @ 2022-08-27 23:04  shigp1  阅读(95)  评论(0编辑  收藏  举报