服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - mybatis xml文件热加载实现示例详解

mybatis xml文件热加载实现示例详解

2023-03-27 14:31wayn Java教程

这篇文章主要为大家介绍了mybatis xml文件热加载实现示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

引言

本文博主给大家带来一篇 mybatis xml 文件热加载的实现教程,自博主从事开发工作使用 Mybatis 以来,如果需要修改 xml 文件的内容,通常都需要重启项目,因为不重启的话,修改是不生效的,Mybatis 仅仅会在项目初始化的时候将 xml 文件加载进内存。

本着提升开发效率且网上没有能够直接使用的轮子初衷,博主自己开发了 mybatis-xmlreload-spring-boot-starter 这个项目。它能够帮助我们在Spring Boot + Mybatis的开发环境中修改 xml 后,不需要重启项目就能让修改过后 xml 文件立即生效,实现热加载功能。这里先给出项目地址:

mybatis xml文件热加载实现示例详解

一、xml 文件热加载实现原理

 

1.1 xml 文件怎么样解析

在Spring Boot + Mybatis的常规项目中,通过 org.mybatis.spring.SqlSessionFactoryBean 这个类的 buildSqlSessionFactory() 方法完成对 xml 文件的加载逻辑,这个方法只会在自动配置类 MybatisAutoConfiguration 初始化操作时进行调用。这里把 buildSqlSessionFactory() 方法中 xml 解析核心部分进行展示如下:

mybatis xml文件热加载实现示例详解

  • 通过遍历 this.mapperLocations 数组(这个对象就是保存了编译后的所有 xml 文件)完成对所有 xml 文件的解析以及加载进内存。this.mapperLocations 解析逻辑在 MybatisProperties 类的 resolveMapperLocations() 方法中,它会解析 mybatis.mapperLocations 属性中的 xml 路径,将编译后的 xml 文件读取进 Resource 数组中。路径解析的核心逻辑在 PathMatchingResourcePatternResolver 类的 getResources(String locationPattern) 方法中。大家有兴趣可以自己研读一下,这里不多做介绍。

通过 xmlMapperBuilder.parse() 方法解析 xml 文件各个节点,解析方法如下:

mybatis xml文件热加载实现示例详解

简单来说,这个方法会解析 xml 文件中的 mapper|resultMap|cache|cache-ref|sql|select|insert|update|delete 等标签。将他们保存在 org.apache.ibatis.session.Configuration 类的对应属性中,如下展示:

mybatis xml文件热加载实现示例详解

到这里,我们就知道了 Mybatis 对 xml 文件解析是通过 xmlMapperBuilder.parse() 方法完成并且只会在项目启动时加载 xml 文件。

1.2 实现思路

通过对上述 xml 解析逻辑进行分析,我们可以通过监听 xml 文件的修改,当监听到修改操作时,直接调用 xmlMapperBuilder.parse() 方法,将修改过后的 xml 文件进行重新解析,并替换内存中的对应属性以此完成热加载操作。这里也就引出了本文所讲的主角:mybatis-xmlreload-spring-boot-starter

二、mybatis-xmlreload-spring-boot-starter 登场

mybatis-xmlreload-spring-boot-starter 这个项目完成了博主上述的实现思路,使用技术如下:

  • 修改 xml 文件的加载逻辑。在原用 mybatis-spring 中,只会加载项目编译过后的 xml 文件,也就是 target 目录下的 xml 文件。但是在mybatis-xmlreload-spring-boot-starter中,我修改了这一点,它会加载项目 resources 目录下的 xml 文件,这样对于 xml 文件的修改操作是可以立马触发热加载的。
  • 通过 io.methvin.directory-watcher 来监听 xml 文件的修改操作,它底层是通过 java.nio 的WatchService 来实现。
  • 兼容 Mybatis-plus3.0,核心代码兼容了 Mybatis-plus 自定义的 com.baomidou.mybatisplus.core.MybatisConfiguration 类,任然可以使用 xml 文件热加载功能。

2.1 核心代码

项目的结构如下:

mybatis xml文件热加载实现示例详解

核心代码在 MybatisXmlReload 类中,代码展示:

  1. /**
  2. * mybatis-xml-reload核心xml热加载逻辑
  3. */
  4. public class MybatisXmlReload {
  5. private static final Logger logger = LoggerFactory.getLogger(MybatisXmlReload.class);
  6. /**
  7. * 是否启动以及xml路径的配置类
  8. */
  9. private MybatisXmlReloadProperties prop;
  10. /**
  11. * 获取项目中初始化完成的SqlSessionFactory列表,对多数据源进行处理
  12. */
  13. private List<SqlSessionFactory> sqlSessionFactories;
  14. public MybatisXmlReload(MybatisXmlReloadProperties prop, List<SqlSessionFactory> sqlSessionFactories) {
  15. this.prop = prop;
  16. this.sqlSessionFactories = sqlSessionFactories;
  17. }
  18. public void xmlReload() throws IOException {
  19. PathMatchingResourcePatternResolver patternResolver = new PathMatchingResourcePatternResolver();
  20. String CLASS_PATH_TARGET = File.separator + "target" + File.separator + "classes";
  21. String MAVEN_RESOURCES = "/src/main/resources";
  22. // 1. 解析项目所有xml路径,获取xml文件在target目录中的位置
  23. List<Resource> mapperLocationsTmp = Stream.of(Optional.of(prop.getMapperLocations()).orElse(new String[0]))
  24. .flatMap(location -> Stream.of(getResources(patternResolver, location))).toList();
  25. List<Resource> mapperLocations = new ArrayList<>(mapperLocationsTmp.size() * 2);
  26. Set<Path> locationPatternSet = new HashSet<>();
  27. // 2. 根据xml文件在target目录下的位置,进行路径替换找到该xml文件在resources目录下的位置
  28. for (Resource mapperLocation : mapperLocationsTmp) {
  29. mapperLocations.add(mapperLocation);
  30. String absolutePath = mapperLocation.getFile().getAbsolutePath();
  31. File tmpFile = new File(absolutePath.replace(CLASS_PATH_TARGET, MAVEN_RESOURCES));
  32. if (tmpFile.exists()) {
  33. locationPatternSet.add(Path.of(tmpFile.getParent()));
  34. FileSystemResource fileSystemResource = new FileSystemResource(tmpFile);
  35. mapperLocations.add(fileSystemResource);
  36. }
  37. }
  38. // 3. 对resources目录的xml文件修改进行监听
  39. List<Path> rootPaths = new ArrayList<>();
  40. rootPaths.addAll(locationPatternSet);
  41. DirectoryWatcher watcher = DirectoryWatcher.builder()
  42. .paths(rootPaths) // or use paths(directoriesToWatch)
  43. .listener(event -> {
  44. switch (event.eventType()) {
  45. case CREATE: /* file created */
  46. break;
  47. case MODIFY: /* file modified */
  48. Path modifyPath = event.path();
  49. String absolutePath = modifyPath.toFile().getAbsolutePath();
  50. logger.info("mybatis xml file has changed:" + modifyPath);
  51. // 4. 对多个数据源进行遍历,判断修改过的xml文件属于那个数据源
  52. for (SqlSessionFactory sqlSessionFactory : sqlSessionFactories) {
  53. try {
  54. // 5. 获取Configuration对象
  55. Configuration targetConfiguration = sqlSessionFactory.getConfiguration();
  56. Class<?> tClass = targetConfiguration.getClass(), aClass = targetConfiguration.getClass();
  57. if (targetConfiguration.getClass().getSimpleName().equals("MybatisConfiguration")) {
  58. aClass = Configuration.class;
  59. }
  60. Set<String> loadedResources = (Set<String>) getFieldValue(targetConfiguration, aClass, "loadedResources");
  61. loadedResources.clear();
  62. Map<String, ResultMap> resultMaps = (Map<String, ResultMap>) getFieldValue(targetConfiguration, tClass, "resultMaps");
  63. Map<String, XNode> sqlFragmentsMaps = (Map<String, XNode>) getFieldValue(targetConfiguration, tClass, "sqlFragments");
  64. Map<String, MappedStatement> mappedStatementMaps = (Map<String, MappedStatement>) getFieldValue(targetConfiguration, tClass, "mappedStatements");
  65. // 6. 遍历xml文件
  66. for (Resource mapperLocation : mapperLocations) {
  67. // 7. 判断是否是被修改过的xml文件,否则跳过
  68. if (!absolutePath.equals(mapperLocation.getFile().getAbsolutePath())) {
  69. continue;
  70. }
  71. // 8. 重新解析xml文件,替换Configuration对象的相对应属性
  72. XPathParser parser = new XPathParser(mapperLocation.getInputStream(), true, targetConfiguration.getVariables(), new XMLMapperEntityResolver());
  73. XNode mapperXnode = parser.evalNode("/mapper");
  74. List<XNode> resultMapNodes = mapperXnode.evalNodes("/mapper/resultMap");
  75. String namespace = mapperXnode.getStringAttribute("namespace");
  76. for (XNode xNode : resultMapNodes) {
  77. String id = xNode.getStringAttribute("id", xNode.getValueBasedIdentifier());
  78. resultMaps.remove(namespace + "." + id);
  79. }
  80. List<XNode> sqlNodes = mapperXnode.evalNodes("/mapper/sql");
  81. for (XNode sqlNode : sqlNodes) {
  82. String id = sqlNode.getStringAttribute("id", sqlNode.getValueBasedIdentifier());
  83. sqlFragmentsMaps.remove(namespace + "." + id);
  84. }
  85. List<XNode> msNodes = mapperXnode.evalNodes("select|insert|update|delete");
  86. for (XNode msNode : msNodes) {
  87. String id = msNode.getStringAttribute("id", msNode.getValueBasedIdentifier());
  88. mappedStatementMaps.remove(namespace + "." + id);
  89. }
  90. try {
  91. // 9. 重新加载和解析被修改的 xml 文件
  92. XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(mapperLocation.getInputStream(),
  93. targetConfiguration, mapperLocation.toString(), targetConfiguration.getSqlFragments());
  94. xmlMapperBuilder.parse();
  95. } catch (Exception e) {
  96. logger.error(e.getMessage(), e);
  97. }
  98. logger.info("Parsed mapper file: '" + mapperLocation + "'");
  99. }
  100. } catch (Exception e) {
  101. logger.error(e.getMessage(), e);
  102. }
  103. }
  104. break;
  105. case DELETE: /* file deleted */
  106. break;
  107. }
  108. })
  109. .build();
  110. ThreadFactory threadFactory = r -> {
  111. Thread thread = new Thread(r);
  112. thread.setName("xml-reload");
  113. thread.setDaemon(true);
  114. return thread;
  115. };
  116. watcher.watchAsync(new ScheduledThreadPoolExecutor(1, threadFactory));
  117. }
  118. /**
  119. * 根据xml路径获取对应实际文件
  120. *
  121. * @param location 文件位置
  122. * @return Resource[]
  123. */
  124. private Resource[] getResources(PathMatchingResourcePatternResolver patternResolver, String location) {
  125. try {
  126. return patternResolver.getResources(location);
  127. } catch (IOException e) {
  128. return new Resource[0];
  129. }
  130. }
  131. /**
  132. * 根据反射获取 Configuration 对象中属性
  133. */
  134. private static Object getFieldValue(Configuration targetConfiguration, Class<?> aClass,
  135. String filed) throws NoSuchFieldException, IllegalAccessException {
  136. Field resultMapsField = aClass.getDeclaredField(filed);
  137. resultMapsField.setAccessible(true);
  138. return resultMapsField.get(targetConfiguration);
  139. }
  140. }

代码执行逻辑:

  • 解析配置文件指定的 xml 路径,获取 xml 文件在 target 目录下的位置
  • 根据 xml 文件在 target 目录下的位置,进行路径替换找到 xml 文件所在 resources 目录下的位置
  • 对 resources 目录的 xml 文件的修改操作进行监听
  • 对多个数据源进行遍历,判断修改过的 xml 文件属于那个数据源
  • 根据 Configuration 对象获取对应的标签属性
  • 遍历 resources 目录下 xml 文件列表
  • 判断是否是被修改过的 xml 文件,否则跳过
  • 解析被修改的 xml 文件,替换 Configuration 对象中的相对应属性
  • 重新加载和解析被修改的 xml 文件

2.2 安装方式

  • Spring Boot3.0 中,当前博主提供了mybatis-xmlreload-spring-boot-starter在 Maven 项目中的坐标地址如下
  1. <dependency>
  2. <groupId>com.wayn</groupId>
  3. <artifactId>mybatis-xmlreload-spring-boot-starter</artifactId>
  4. <version>3.0.3.m1</version>
  5. </dependency>
  • Spring Boot2.0 Maven 项目中的坐标地址如下
  1. <dependency>
  2. <groupId>com.wayn</groupId>
  3. <artifactId>mybatis-xmlreload-spring-boot-starter</artifactId>
  4. <version>2.0.1.m1</version>
  5. </dependency>

2.3 使用配置

Maven 项目写入mybatis-xmlreload-spring-boot-starter坐标后即可使用本项目功能,默认是不启用 xml 文件的热加载功能,想要开启的话通过在项目配置文件中设置 mybatis-xml-reload.enabled 为 true,并指定 mybatis-xml-reload.mapper-locations 属性,也就是 xml 文件位置即可启动。具体配置如下:

  1. # mybatis xml文件热加载配置
  2. mybatis-xml-reload:
  3. # 是否开启 xml 热更新,true开启,false不开启,默认为false
  4. enabled: true
  5. # xml文件位置,eg: `classpath*:mapper/**/*Mapper.xml,classpath*:other/**/*Mapper.xml`
  6. mapper-locations: classpath:mapper/*Mapper.xml

最后

欢迎大家使用mybatis-xmlreload-spring-boot-starter,使用中遇到问题可以提交 issue 或者加博主私人微信waynaqua给你解决。 再附项目地址:

希望这个项目能够提升大家的日常开发效率,节约重启次数

以上就是mybatis xml文件热加载实现示例详解的详细内容,更多关于mybatis xml文件热加载的资料请关注服务器之家其它相关文章!

原文链接:https://juejin.cn/post/7214396380353331256

延伸 · 阅读

精彩推荐