XPathParser类

XPathParser类是mybatis对 javax.xml.xpath.XPath的包装类。
接下来我们来看下XPathParser类的结构

1、属性

  //  存放读取到的整个XML文档
  private final Document document;
  //  是否开启验证
  private boolean validation;
  // 自定义的DTD约束文件实体解析器,与validation配合使用
  private EntityResolver entityResolver;
  // MyBatis配置文件中的properties节点的信息
  private Properties variables;
  //  XPath工具
  private XPath xpath;

2、构造函数

在这里插入图片描述

 public XPathParser(String xml) {
   commonConstructor(false, null, null);
   this.document = createDocument(new InputSource(new StringReader(xml)));
 }

构造方法包含两部分:

  • 初始化属性
private void commonConstructor(boolean validation, Properties variables, EntityResolver entityResolver) {
   this.validation = validation;
   this.entityResolver = entityResolver;
   this.variables = variables;
   XPathFactory factory = XPathFactory.newInstance();
   this.xpath = factory.newXPath();
}
  • 构建XML文档对应的Document
private Document createDocument(InputSource inputSource) {
    // important: this must only be called AFTER common constructor
    try {
      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
      factory.setValidating(validation);

      factory.setNamespaceAware(false);
      factory.setIgnoringComments(true);
      factory.setIgnoringElementContentWhitespace(false);
      factory.setCoalescing(false);
      factory.setExpandEntityReferences(true);

      DocumentBuilder builder = factory.newDocumentBuilder();
      builder.setEntityResolver(entityResolver);
      builder.setErrorHandler(new ErrorHandler() {
        @Override
        public void error(SAXParseException exception) throws SAXException {
          throw exception;
        }

        @Override
        public void fatalError(SAXParseException exception) throws SAXException {
          throw exception;
        }

        @Override
        public void warning(SAXParseException exception) throws SAXException {
        }
      });
      return builder.parse(inputSource);
    } catch (Exception e) {
      throw new BuilderException("Error creating document instance.  Cause: " + e, e);
    }
}

3、方法

在这里插入图片描述
基本类型的解析方法,最终调用的都是方法 evalString(Object root, String expression)

  private Properties variables;
  private XPath xpath;
  
  public String evalString(Object root, String expression) {
    // 解析结果
    String result = (String) evaluate(expression, root, XPathConstants.STRING);
    // 对${}变量从Properties配置文件中进行查找相应的属性值替换,若variables为空或未查找到${}直接返回result
    result = PropertyParser.parse(result, variables);
    return result;
  }

  private Object evaluate(String expression, Object root, QName returnType) {
    try {
      // 调用XPath进行解析
      return xpath.evaluate(expression, root, returnType);
    } catch (Exception e) {
      throw new BuilderException("Error evaluating XPath.  Cause: " + e, e);
    }
  }

4、总结

可使用XPathParser类来解析自己定义的XML文件,同时也可以仿照mybatis定义自己的Properties文件类替换XML文件中的变量值

        String path = "E:\\GitResource\\springboot-bucket\\springboot-mybatis\\src\\main\\resources\\mapper\\20240729.xml";
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document document = documentBuilder.parse(path);

        XPathParser xPathParser = new XPathParser(document,false,null,null);
        String evalString = xPathParser.evalString("/mapper/sql[1]");
        System.out.println(evalString);
  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
XMLConfigBuilder是MyBatis框架中用于解析mybatis-config.xml配置文件的,它采用工厂模式进行设计。下面是XMLConfigBuilder对应的源码,并对其进行解释: ```java public class XMLConfigBuilder extends BaseBuilder { private boolean parsed; private final XPathParser parser; private String environment; private final ReflectorFactory localReflectorFactory = new DefaultReflectorFactory(); private final MapperBuilderAssistant builderAssistant; private final Map<String, XNode> sqlFragments = new HashMap<String, XNode>(); public XMLConfigBuilder(Reader reader, String environment, Properties props) { this(new XPathParser(reader, true, props, new XMLMapperEntityResolver()), environment, props); } public XMLConfigBuilder(InputStream inputStream, String environment, Properties props) { this(new XPathParser(inputStream, true, props, new XMLMapperEntityResolver()), environment, props); } private XMLConfigBuilder(XPathParser parser, String environment, Properties props) { super(new Configuration()); this.builderAssistant = new MapperBuilderAssistant(configuration, null); this.parsed = false; this.environment = environment; this.parser = parser; this.configuration.setVariables(props); } public Configuration parse() { if (parsed) { throw new BuilderException("Each XMLConfigBuilder can only be used once."); } parsed = true; parseConfiguration(parser.evalNode("/configuration")); return configuration; } private void parseConfiguration(XNode root) { try { //解析properties节点,将其中的属性值设置到Configuration对象中 propertiesElement(root.evalNode("properties")); //解析settings节点,将其中的配置设置到Configuration对象中 Properties settings = settingsAsProperties(root.evalNode("settings")); loadCustomVfs(settings); loadCustomLogImpl(settings); //解析typeAliases节点,将其中的别名注册到Configuration对象中 typeAliasesElement(root.evalNode("typeAliases")); //解析plugins节点,将其中的插件添加到InterceptorChain对象中 pluginElement(root.evalNode("plugins")); //解析objectFactory节点,将其中的实现设置到Configuration对象中 objectFactoryElement(root.evalNode("objectFactory")); //解析objectWrapperFactory节点,将其中的实现设置到Configuration对象中 objectWrapperFactoryElement(root.evalNode("objectWrapperFactory")); //解析reflectorFactory节点,将其中的实现设置到Configuration对象中 reflectorFactoryElement(root.evalNode("reflectorFactory")); //将settings节点中的配置设置到Configuration对象中 settingsElement(settings); //解析environments节点,将其中的环境注册到Configuration对象中 environmentsElement(root.evalNode("environments")); //解析databaseIdProvider节点,将其中的实现设置到Configuration对象中 databaseIdProviderElement(root.evalNode("databaseIdProvider")); //解析typeHandlers节点,将其中的型处理器注册到Configuration对象中 typeHandlerElement(root.evalNode("typeHandlers")); //解析mappers节点,将其中的Mapper接口注册到Configuration对象中 mapperElement(root.evalNode("mappers")); } catch (Exception e) { throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e); } } //省略其他方法... } ``` XMLConfigBuilder的构造方法中,接收一个XPathParser对象、一个环境名和一个Properties对象。其中,XPathParser对象用于解析XML文件,环境名用于指定当前使用的是哪个环境的配置,Properties对象用于保存一些配置属性。 XMLConfigBuilder的parse()方法用于解析mybatis-config.xml配置文件,它首先检查是否已经解析过该文件,如果解析过则抛出异常。然后它调用parseConfiguration()方法进行具体的解析,解析mybatis-config.xml中的各个节点,并将解析结果设置到Configuration对象中。其中,parseConfiguration()方法调用了多个私有方法,用于解析mybatis-config.xml中的各个节点。 这种工厂模式的设计,使得MyBatis框架能够轻松地扩展和维护,只需要添加相应的节点解析方法即可。同时,将解析过程封装到XMLConfigBuilder中,使得MyBatis框架的其他组件可以直接拿到解析好的Configuration对象,方便使用。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值