java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > xml修改mybatis-xmlreload

修改xml文件再也不用重启项目mybatis-xmlreload方法

作者:wayn

这篇文章主要为大家介绍了修改xml文件再也不用重启项目mybatis-xmlreload,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

正文

自博主18年使用 Mybaits 以来,开发环境中如果修改了 xml 文件后,只有重启项目才能生效,如果小项目重启还好,但是对于一个重启需要十几分钟的大型项目来说,这就非常耗时了。开发人员因为修改了xml 文件少量内容,比如添加一个逗号、查询增加一个字段或者修改一个 bug 等,就需要重启整个项目,这就非常痛苦了。

所以在这里给大家推荐一个实现了 Mybatis xml文件热加载的项目,mybatis-xmlreload-spring-boot-starter。它能够帮助我们在Spring Boot + Mybatis的开发环境中修改 xml 后,不需要重启项目就能让修改过后 xml 文件立即生效,实现热加载功能。这里给出项目地址:

ps:mybatis-xmlreload-spring-boot-starter目前 3.0.3.m1 版本实现了 xml 文件修改已有内容,比如修改 sql 语句、添加查询字段、添加查询条件等,可以实现热加载功能。但是对于 xml 文件添加 insert|update|delete|select 标签等内容后,是无法实现热加载的。众所周知,在 Idea 环境进行 Java 开发,在方法内修改方法内容是可以热加载的。但是添加新方法、添加方法参数,修改方法参数,修改方法返回值等都是无法直接热加载的。

一、mybatis-xmlreload-spring-boot-starter使用

mybatis-xmlreload-spring-boot-starter原理:

二、技术原理

mybatis-xmlreload-spring-boot-starter代码结构如下:

核心代码在MybatisXmlReload类中,执行逻辑:

    /**
     * 是否启动以及xml路径的配置类
     */
    private MybatisXmlReloadProperties prop;
    /**
     * 获取项目中初始化完成的SqlSessionFactory列表,对多数据源进行处理
     */
    private List<SqlSessionFactory> sqlSessionFactories;
    public MybatisXmlReload(MybatisXmlReloadProperties prop, 
            List<SqlSessionFactory> sqlSessionFactories) {
        this.prop = prop;
        this.sqlSessionFactories = sqlSessionFactories;
    }
    // 解析项目所有xml路径,获取xml文件在target目录中的位置
    List<Resource> mapperLocationsTmp = Stream.of(Optional.of(prop.getMapperLocations())
    .orElse(new String[0]))
    .flatMap(location -> Stream.of(getResources(patternResolver, location)))
    .toList();
    // 根据xml文件在target目录下的位置,进行路径替换找到该xml文件在resources目录下的位置
    for (Resource mapperLocation : mapperLocationsTmp) {
        mapperLocations.add(mapperLocation);
        String absolutePath = mapperLocation.getFile().getAbsolutePath();
        File tmpFile = new File(absolutePath.replace(CLASS_PATH_TARGET, MAVEN_RESOURCES));
        if (tmpFile.exists()) {
            locationPatternSet.add(Path.of(tmpFile.getParent()));
            FileSystemResource fileSystemResource = new FileSystemResource(tmpFile);
            mapperLocations.add(fileSystemResource);
        }
    }
    // 对resources目录的xml文件修改进行监听
    List<Path> rootPaths = new ArrayList<>();
    rootPaths.addAll(locationPatternSet);
    DirectoryWatcher watcher = DirectoryWatcher.builder()
            .paths(rootPaths) // or use paths(directoriesToWatch)
            .listener(event -> {
                switch (event.eventType()) {
                    case CREATE: /* file created */
                        break;
                    case MODIFY: /* file modified */
                        Path modifyPath = event.path();
                        String absolutePath = modifyPath.toFile().getAbsolutePath();
                        logger.info("mybatis xml file has changed:" + modifyPath);
                        // 执行热加载逻辑...
                        break;
                    case DELETE: /* file deleted */
                        break;
                }
            })
            .build();
    ThreadFactory threadFactory = r -> {
        Thread thread = new Thread(r);
        thread.setName("xml-reload");
        thread.setDaemon(true);
        return thread;
    };
    watcher.watchAsync(new ScheduledThreadPoolExecutor(1, threadFactory));
  // 对多个数据源进行遍历,判断修改过的xml文件属于那个数据源
  for (SqlSessionFactory sqlSessionFactory : sqlSessionFactories) {
      ...
  }
    // 根据 Configuration 对象获取对应的标签属性
    Configuration targetConfiguration = sqlSessionFactory.getConfiguration();
    Class<?> tClass = targetConfiguration.getClass(), aClass = targetConfiguration.getClass();
    if (targetConfiguration.getClass().getSimpleName().equals("MybatisConfiguration")) {
        aClass = Configuration.class;
    }
    Set<String> loadedResources = (Set<String>) getFieldValue(
        targetConfiguration, aClass, "loadedResources");
    loadedResources.clear();
    Map<String, ResultMap> resultMaps = (Map<String, ResultMap>) getFieldValue(
        targetConfiguration, tClass, "resultMaps");
    Map<String, XNode> sqlFragmentsMaps = (Map<String, XNode>) getFieldValue(
        targetConfiguration, tClass, "sqlFragments");
    Map<String, MappedStatement> mappedStatementMaps = 
        (Map<String, MappedStatement>) getFieldValue(
            targetConfiguration, tClass, "mappedStatements");
    // 遍历 resources 目录下 xml 文件列表
    for (Resource mapperLocation : mapperLocations) {
        ...
    }
    // 判断是否是被修改过的xml文件,否则跳过
    if (!absolutePath.equals(mapperLocation.getFile().getAbsolutePath())) {
        continue;
    }
    // 重新解析xml文件,替换Configuration对象的相对应属性
    XPathParser parser = new XPathParser(mapperLocation.getInputStream(), true, 
        targetConfiguration.getVariables(), 
        new XMLMapperEntityResolver());
    XNode mapperXnode = parser.evalNode("/mapper");
    String namespace = mapperXnode.getStringAttribute("namespace");
    List<XNode> resultMapNodes = mapperXnode.evalNodes("/mapper/resultMap");
    for (XNode xNode : resultMapNodes) {
        String id = xNode.getStringAttribute("id", xNode.getValueBasedIdentifier());
        resultMaps.remove(namespace + "." + id);
    }
    List<XNode> sqlNodes = mapperXnode.evalNodes("/mapper/sql");
    for (XNode sqlNode : sqlNodes) {
        String id = sqlNode.getStringAttribute("id", sqlNode.getValueBasedIdentifier());
        sqlFragmentsMaps.remove(namespace + "." + id);
    }
    List<XNode> msNodes = mapperXnode.evalNodes("select|insert|update|delete");
    for (XNode msNode : msNodes) {
        String id = msNode.getStringAttribute("id", msNode.getValueBasedIdentifier());
        mappedStatementMaps.remove(namespace + "." + id);
    }
    // 9. 重新加载和解析被修改的 xml 文件
    try {
        XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(
            mapperLocation.getInputStream(),
            targetConfiguration,
            mapperLocation.toString(), 
            targetConfiguration.getSqlFragments());
        xmlMapperBuilder.parse();
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    }

三、安装方式

<dependency>
    <groupId>com.wayn</groupId>
    <artifactId>mybatis-xmlreload-spring-boot-starter</artifactId>
    <version>3.0.3.m1</version>
</dependency>
<dependency>
    <groupId>com.wayn</groupId>
    <artifactId>mybatis-xmlreload-spring-boot-starter</artifactId>
    <version>2.0.1.m1</version>
</dependency>

四、使用配置

mybatis-xmlreload-spring-boot-starter 目前只有两个配置属性。mybatis-xml-reload.enabled 默认是 false, 也就是不启用 xml 文件的热加载功能,想要开启的话通过在项目配置文件中设置 mybatis-xml-reload.enabled 为 true。还有一个配置属性是 mybatis-xml-reload.mapper-locations,执行热加载的 xml 文件路径,这个属性需要手动填写,跟项目中的 mybatis.mapper-locations 保持一直即可。具体配置如下:

# mybatis xml文件热加载配置
mybatis-xml-reload:
  # 是否开启 xml 热更新,true开启,false不开启,默认为false
  enabled: true 
  # xml文件路径,可以填写多个,逗号分隔。
  # eg: `classpath*:mapper/**/*Mapper.xml,classpath*:other/**/*Mapper.xml`
  mapper-locations: classpath:mapper/*Mapper.xml

五、最后

欢迎大家使用mybatis-xmlreload-spring-boot-starter,这个项目我开源的的,使用中遇到问题可以提交 issue。提交的问题我都会一一查看并回复。再附项目地址:

以上就是修改xml文件再也不用重启项目mybatis-xmlreload的详细内容,更多关于mybatis-xmlreload的资料请关注脚本之家其它相关文章!

您可能感兴趣的文章:
阅读全文