分享一个修改了xml文件再也不用重启的项目mybatis-xmlrelaod

自我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」类中,执行逻辑:

  1. 通过项目初始化时传入 MybatisXmlReloadProperties prop, List sqlSessionFactories 参数,获取「mybatis-xmlreload-spring-boot-starter」的配置信息,以及项目中的数据源配置
/**
 * 是否启动以及xml路径的配置类
 */
private MybatisXmlReloadProperties prop;
/**
 * 获取项目中初始化完成的SqlSessionFactory列表,对多数据源进行处理
 */
private List sqlSessionFactories;
public MybatisXmlReload(MybatisXmlReloadProperties prop, 
        List sqlSessionFactories) {
    this.prop = prop;
    this.sqlSessionFactories = sqlSessionFactories;
}
  1. 解析配置文件指定的 xml 路径,获取 xml 文件在 target 目录下的位置
// 解析项目所有xml路径,获取xml文件在target目录中的位置
List mapperLocationsTmp = Stream.of(
  Optional.of(prop.getMapperLocations())
  .orElse(new String[0]))
  .flatMap(location -> Stream.of(getResources(patternResolver, location)))
  .toList();
  1. 根据 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);
    }
}
  1. 对 resources 目录的 xml 文件的修改操作进行监听
// 对resources目录的xml文件修改进行监听
List 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));
  1. 对多个数据源进行遍历,判断修改过的 xml 文件属于那个数据源
// 对多个数据源进行遍历,判断修改过的xml文件属于那个数据源
for (SqlSessionFactory sqlSessionFactory : sqlSessionFactories) {
    ...
}
  1. 根据 Configuration 对象获取对应的标签属性
// 根据 Configuration 对象获取对应的标签属性
Configuration targetConfiguration = sqlSessionFactory.getConfiguration();
Class<?> tClass = targetConfiguration.getClass(), 
  aClass = targetConfiguration.getClass();
if (targetConfiguration.getClass().getSimpleName()
                                  .equals("MybatisConfiguration")) {
    aClass = Configuration.class;
}
Set loadedResources = (Set) getFieldValue(
    targetConfiguration, aClass, "loadedResources");
loadedResources.clear();

Map resultMaps = (Map) getFieldValue(
    targetConfiguration, tClass, "resultMaps");
Map sqlFragmentsMaps = (Map) getFieldValue(
    targetConfiguration, tClass, "sqlFragments");
Map mappedStatementMaps = 
    (Map) getFieldValue(
        targetConfiguration, tClass, "mappedStatements");
  1. 遍历 resources 目录下 xml 文件列表
// 遍历 resources 目录下 xml 文件列表
for (Resource mapperLocation : mapperLocations) {
    ...
}
  1. 判断是否是被修改过的 xml 文件,否则跳过
// 判断是否是被修改过的xml文件,否则跳过
if (!absolutePath.equals(mapperLocation.getFile().getAbsolutePath())) {
    continue;
}
  1. 解析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 resultMapNodes = mapperXnode.evalNodes("/mapper/resultMap");
for (XNode xNode : resultMapNodes) {
    String id = 
        xNode.getStringAttribute("id", xNode.getValueBasedIdentifier());
    resultMaps.remove(namespace + "." + id);
}

List sqlNodes = mapperXnode.evalNodes("/mapper/sql");
for (XNode sqlNode : sqlNodes) {
    String id = 
        sqlNode.getStringAttribute("id", sqlNode.getValueBasedIdentifier());
    sqlFragmentsMaps.remove(namespace + "." + id);
}

List msNodes = mapperXnode.evalNodes("select|insert|update|delete");
for (XNode msNode : msNodes) {
    String id = 
        msNode.getStringAttribute("id", msNode.getValueBasedIdentifier());
    mappedStatementMaps.remove(namespace + "." + id);
}
  1. 重新加载和解析被修改的 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);
}

三、安装方式


    com.wayn
    mybatis-xmlreload-spring-boot-starter
    3.0.3.m1

    com.wayn
    mybatis-xmlreload-spring-boot-starter
    2.0.1.m1

四、使用配置

「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。提交的问题我都会一一查看并回复。再附项目地址:

最后再说一句,感兴趣的朋友可以点赞加关注,你的支持将是我更新动力。

展开阅读全文

页面更新:2024-03-14

标签:文件   项目   遍历   数据源   路径   属性   逻辑   加载   位置   方法

1 2 3 4 5

上滑加载更多 ↓
推荐阅读:
友情链接:
更多:

本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828  

© CopyRight 2020-2024 All Rights Reserved. Powered By 71396.com 闽ICP备11008920号-4
闽公网安备35020302034903号

Top