<?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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!--spring基本注解支持 -->
<context:annotation-config/> <!--mvc注解支持-->
<mvc:annotation-driven/> <!--自动扫描装配-->
<context:component-scan base-package="com.example.demo"/>
</beans>
public class DocumentTest {
@Test
public void doParse() throws IOException, ParserConfigurationException, SAXException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
InputStream inputStream = new FileInputStream(new File("E:\\IdeaProjects\\demo-springmvc\\src\\main\\webapp\\WEB-INF\\dispatcher-servlet2.xml"));
InputSource inputSource = new InputSource(inputStream);
DocumentBuilder docBuilder = factory.newDocumentBuilder();
Document document = docBuilder.parse(inputSource);
Element root = document.getDocumentElement();
System.out.println(root.getNodeName() + "----" + root.getNamespaceURI());
NodeList nodeList = root.getChildNodes(); for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
if (node instanceof Element) {
System.out.println(node.getNodeName() + "----" + node.getNamespaceURI());
}
}
}
}

通过xmlNode获取到它在那个命名空间下,从而通过配置命名空间的解析类进行相关处理

public class DefaultBeanDefinitionDocumentReader implements BeanDefinitionDocumentReader {
@Override
public void registerBeanDefinitions(Document doc, XmlReaderContext readerContext) {
this.readerContext = readerContext;
logger.debug("Loading bean definitions");
Element root = doc.getDocumentElement();
doRegisterBeanDefinitions(root);
} 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.isInfoEnabled()) {
logger.info("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;
} 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);
}
}
}

import、alias、bean、beans(http://www.springframework.org/schema/beans命名空间下)使用parseDefaultElement方法解析

    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)) {
processBeanDefinition(ele, delegate);
}
else if (delegate.nodeNameEquals(ele, NESTED_BEANS_ELEMENT)) {
// recurse
doRegisterBeanDefinitions(ele);
}
}

其他的标签使用parseCustomElement方法解析

    public BeanDefinition parseCustomElement(Element ele) {
return parseCustomElement(ele, null);
} public BeanDefinition parseCustomElement(Element ele, BeanDefinition containingBd) {
String namespaceUri = getNamespaceURI(ele);
NamespaceHandler handler = this.readerContext.getNamespaceHandlerResolver().resolve(namespaceUri);// this.readerContext = new XmlReaderContext();// handler =
if (handler == null) {
error("Unable to locate Spring NamespaceHandler for XML schema namespace [" + namespaceUri + "]", ele);
return null;
}
return handler.parse(ele, new ParserContext(this.readerContext, this, containingBd));
}
public class XmlReaderContext extends ReaderContext {

    public XmlReaderContext(
Resource resource, ProblemReporter problemReporter,
ReaderEventListener eventListener, SourceExtractor sourceExtractor,
XmlBeanDefinitionReader reader, NamespaceHandlerResolver namespaceHandlerResolver) { super(resource, problemReporter, eventListener, sourceExtractor);
this.reader = reader;
this.namespaceHandlerResolver = namespaceHandlerResolver;// namespaceHandlerResolver = new DefaultNamespaceHandlerResolver();
}
}
public class DefaultNamespaceHandlerResolver implements NamespaceHandlerResolver {
@Override
public NamespaceHandler resolve(String namespaceUri) {
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.init();
handlerMappings.put(namespaceUri, namespaceHandler);
return namespaceHandler;
}
catch (ClassNotFoundException ex) {
throw new FatalBeanException("NamespaceHandler class [" + className + "] for namespace [" +
namespaceUri + "] not found", ex);
}
catch (LinkageError err) {
throw new FatalBeanException("Invalid NamespaceHandler class [" + className + "] for namespace [" +
namespaceUri + "]: problem with handler class file or dependent class", err);
}
}
}
}

http://www.springframework.org/schema/context命名空间下的handler

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

http://www.springframework.org/schema/mvc命名空间下的handler

http\://www.springframework.org/schema/mvc=org.springframework.web.servlet.config.MvcNamespaceHandler
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());
} }

parse

public class AnnotationConfigBeanDefinitionParser implements BeanDefinitionParser {

    @Override
public BeanDefinition parse(Element element, ParserContext parserContext) {
Object source = parserContext.extractSource(element); // Obtain bean definitions for all relevant BeanPostProcessors.
Set<BeanDefinitionHolder> processorDefinitions =
AnnotationConfigUtils.registerAnnotationConfigProcessors(parserContext.getRegistry(), source); // Register component for the surrounding <context:annotation-config> element.
CompositeComponentDefinition compDefinition = new CompositeComponentDefinition(element.getTagName(), source);
parserContext.pushContainingComponent(compDefinition); // Nest the concrete beans in the surrounding component.
for (BeanDefinitionHolder processorDefinition : processorDefinitions) {
parserContext.registerComponent(new BeanComponentDefinition(processorDefinition));
} // Finally register the composite component.
parserContext.popAndRegisterContainingComponent(); return null;
} }

Java笔记Spring(八)的更多相关文章

  1. Java笔记Spring(七)

    DispatcherServlet初始化,继续分析日志 主要部分: 23-May-2018 17:47:55.457 INFO [RMI TCP Connection(3)-127.0.0.1] or ...

  2. Java笔记Spring(五)

    C:\apache-tomcat-8.0.36\bin\catalina.bat run [2018-05-23 02:30:31,657] Artifact demo-springmvc:war e ...

  3. Java笔记Spring(四)

    spring web项目启动入口 1.首先看一下传统Java Web的配置文件web.xml,网上找的一个,参考地址:https://blog.csdn.net/github_36301064/art ...

  4. Java笔记Spring(一)

    一.Spring框架 源码地址:https://github.com/spring-projects/spring-framework 构建工具:Gradle,Gradle教程:https://www ...

  5. Effective java笔记(八),异常

    57.只针对异常的情况才使用异常 try { int i = 0; while(true) range[i++].climb(); }catch(ArrayIndexOutOfBoundsExcept ...

  6. Java笔记(十八)……包

    概述 对类文件进行分类管理. 给类提供多层命名空间. 写在程序文件的第一行. 类名的全称的是 包名.类名. 包也是一种封装形式. 访问权限 引用<The Complete Reference&g ...

  7. Java笔记Spring(六)

    web.xml各节点加载顺序 <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns=&q ...

  8. Java笔记Spring(三)

    spring-beans和spring-context 一.注解 1.自定义一个注解 @Target({ElementType.METHOD}) @Retention(RetentionPolicy. ...

  9. Java笔记Spring(二)

    spring-core 通过Gradle构建工具,转换包的命名空间为org.springframework下 cglib包,net.sf.cglib -> org.springframework ...

随机推荐

  1. Mysql数据库账户权限设置

    1.修改mysql数据库的root密码: 修改 数据库.表名 SET password=加密(‘密码’) where user=’root’; UPDATE mysql.user SET passwo ...

  2. 复杂透视表的SQL生成方法

    一般而言,利用表单查看数据时,会从不同的维度来涉及透视表.比如,从产品和时间维度分析销售数据. 当需要从时间维度去分析时,同时希望能有同比,环比数据,那么将时间维度设计成列将极大方便SQL的编写. 如 ...

  3. leetcode 687.Longest Univalue Path

    寻找最长的路径,那么会在左边或者右边或者是从左到跟然后再到右方的路径的. /** * Definition for a binary tree node. * struct TreeNode { * ...

  4. vue 通知 走马灯效果

    封装一个子组件: <template> <div class="container"> <div class="wrap"> ...

  5. 认识Ajax

    1.简介 AJAX 相当于异步 JavaScript 和 XML,是一种用于创建快速动态网页的技术.通过在后台与服务器进行少量数据交换,AJAX 可以使网页实现异步更新.这意味着可以在不重新加载整个网 ...

  6. 小妖精的完美游戏教室——人工智能,A*算法,实现篇

    //================================================================//// Copyright (C) 2017 Team Saluk ...

  7. zoj 2524 并查集裸

    Description There are so many different religions in the world today that it is difficult to keep tr ...

  8. C++ operator 学习

    1.概述 1.1what operator 是c++的一个关键字,和运算符如(=)一起使用,表示一个运算符重载函数 1.2why 对于C++提供的所有操作符,通常只支持对于基本数据类型和标准库中提供的 ...

  9. git忽视上传规则文件 .gitignore

    语法 语法 作用 例子 "/" 忽略根目录下的文件 /data "*" 忽略所有文件 *.txt => 1.txt,2.txt... "?&qu ...

  10. hibernate的lazy初始化结果

    package com.ehcache; import java.io.Serializable; public class User implements Serializable{ private ...