温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

怎么使用mybatis-xmlreload实现修改xml文件再也不用重启项目

发布时间:2023-03-27 15:29:25 来源:亿速云 阅读:122 作者:iii 栏目:开发技术

今天小编给大家分享一下怎么使用mybatis-xmlreload实现修改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原理:

  • 修改 xml 文件的加载逻辑。在普通的 mybatis-spring 项目中,默认只会加载项目编译过后的 xml 文件,也就是 target 目录下的 xml 文件。但是在mybatis-xmlreload-spring-boot-starter中,修改了这一点,它会加载项目 resources 目录下的 xml 文件,这样用户对于 resources 目录下 xml 文件的修改操作是可以立即触发热加载的。

  • 通过 io.methvin.directory-watcher 项目来监听 xml 文件的修改操作,它底层是通过 java.nio 的WatchService 来实现,当我们监听了整个 resources 目录后,xml 文件的修改会立马触发 MODIFY 事件。

  • 通过 mybatis-spring 项目原生的 xmlMapperBuilder.parse() 方法重新加载解析修改过后的 xml 文件来保证项目对于 Mybatis 的兼容性处理。

二、技术原理

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

怎么使用mybatis-xmlreload实现修改xml文件再也不用重启项目

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

  • 通过项目初始化时传入 MybatisXmlReloadProperties prop, List<SqlSessionFactory> sqlSessionFactories 参数,获取mybatis-xmlreload-spring-boot-starter的配置信息,以及项目中的数据源配置

    /**
     * 是否启动以及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 目录下的位置

    // 解析项目所有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 目录下的位置

    // 根据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 文件的修改操作进行监听

    // 对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 文件属于那个数据源

  // 对多个数据源进行遍历,判断修改过的xml文件属于那个数据源
  for (SqlSessionFactory sqlSessionFactory : sqlSessionFactories) {
      ...
  }
  • 根据 Configuration 对象获取对应的标签属性

    // 根据 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 文件列表

    // 遍历 resources 目录下 xml 文件列表
    for (Resource mapperLocation : mapperLocations) {
        ...
    }
  • 判断是否是被修改过的 xml 文件,否则跳过

    // 判断是否是被修改过的xml文件,否则跳过
    if (!absolutePath.equals(mapperLocation.getFile().getAbsolutePath())) {
        continue;
    }
  • 解析xml文件,获取修改后的xml文件标签对应的 resultMaps|sqlFragmentsMaps|mappedStatementMaps 的属性并执行替换逻辑,并且兼容 mybatis-plus 的替换逻辑

    // 重新解析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);
    }
  • 重新加载和解析被修改的 xml 文件

    // 9. 重新加载和解析被修改的 xml 文件
    try {
        XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(
            mapperLocation.getInputStream(),
            targetConfiguration,
            mapperLocation.toString(), 
            targetConfiguration.getSqlFragments());
        xmlMapperBuilder.parse();
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    }

三、安装方式

  • Spring Boot3.0 中,mybatis-xmlreload-spring-boot-starter在 Maven 项目提供坐标地址如下:

<dependency>
    <groupId>com.wayn</groupId>
    <artifactId>mybatis-xmlreload-spring-boot-starter</artifactId>
    <version>3.0.3.m1</version>
</dependency>
  • Spring Boot2.0 Maven 项目提供坐标地址如下:

<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实现修改xml文件再也不用重启项目”这篇文章的所有内容,感谢各位的阅读!相信大家阅读完这篇文章都有很大的收获,小编每天都会为大家更新不同的知识,如果还想学习更多的知识,请关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

xml
AI