├── .gitignore ├── LICENSE ├── README.md ├── images └── wx-mp-code.png ├── pom.xml └── src └── main ├── java └── io │ └── github │ └── wayn111 │ └── mybatis │ └── xmlreload │ ├── MybatisXmlReload.java │ └── autoconfiguration │ ├── MybatisXmlReloadConfiguration.java │ └── MybatisXmlReloadProperties.java └── resources └── META-INF ├── additional-spring-configuration-metadata.json ├── spring.factories └── spring └── org.springframework.boot.autoconfigure.AutoConfiguration.imports /.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | .settings 3 | .classpath 4 | .project 5 | *.epoch 6 | *.log 7 | *.iml 8 | .idea 9 | 10 | .factorypath 11 | .mvn/wrapper/maven-wrapper.jar 12 | *.releaseBackup 13 | release.properties 14 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # mybatis-xmlreload-spring-boot-starter 2 | mybatis-xmlreload-spring-boot-starter 支持xml文件热更新功能。Spring Boot2.0项目请使用 2.0.5.m3 版本。 3 | 4 | | 分支名称 | Spring Boot版本 | Mybatis Xmlreload版本 | 5 | |--------------------------------------------------------------------------------------------------|---------------|---------------------| 6 | | [main](https://github.com/wayn111/mybatis-xmlreload-spring-boot-starter) | 3.0.4 | 3.0.5.m3 | 7 | | [springboot2](https://github.com/wayn111/mybatis-xmlreload-spring-boot-starter/tree/springboot2) | 2.2.7.RELEASE | 2.0.5.m3 | 8 | --- 9 | # 原理 10 | - 修改 xml 文件的加载逻辑。在普通的 mybatis-spring 项目中,默认只会加载项目编译过后的 xml 文件,也就是 target 目录下的 xml 文件。但是在mybatis-xmlreload-spring-boot-starter中,修改了这一点,它会加载 Maven 项目中 resources 或者 java 目录下的 xml 文件,这样用户对于 resources 或者 java 目录下 xml 文件的修改操作是可以立即触发热加载的。 11 | - 通过 io.methvin.directory-watcher 项目来监听 xml 文件的修改操作,它底层是通过 java.nio 的WatchService 来实现,当我们监听了整个 resources 目录后,xml 文件的修改会立马触发 MODIFY 事件。 12 | - 通过 mybatis-spring 项目原生的 xmlMapperBuilder.parse() 方法重新加载解析修改过后的 xml 文件来保证项目对于 Mybatis 的兼容性处理。 13 | 14 | # 兼容 15 | - 在 `Spring Boot` 项目中,兼容 `mybatis-spring-boot-starter` 2.0及以上版本。 16 | - 兼容 `mybatis plus`。 17 | 18 | # 安装 19 | 在 Spring Boot3.0 Maven 项目提供坐标地址如下: 20 | ```xml 21 | 22 | io.github.wayn111 23 | mybatis-xmlreload-spring-boot-starter 24 | 3.0.5.m3 25 | 26 | ``` 27 | 在 Spring Boot2.0 Maven 项目提供坐标地址如下: 28 | 29 | ```xml 30 | 31 | io.github.wayn111 32 | mybatis-xmlreload-spring-boot-starter 33 | 2.0.5.m3 34 | 35 | ``` 36 | 37 | # 使用配置 38 | **mybatis-xmlreload-spring-boot-starter** 目前只有两个配置属性。 39 | - `mybatis-xml-reload.enabled` 默认是 false, 也就是不启用 xml 文件的热加载功能,想要开启的话通过在项目配置文件中设置 `mybatis-xml-reload.enabled` 为true。 40 | - `mybatis-xml-reload.mapper-locations`需要热加载的 xml 文件路径,这个属性需要手动填写, 41 | 跟项目中的 `mybatis.mapper-locations` 保持一致即可。如果是多数据源配置,这里可以用逗号分割填写多个路径。 42 | 也可以直接设置xml文件所在目录的绝对路径,例如 file:/E:/GitRepo/newbeemall-pro/src/main/resources/mapper/*.xml 43 | 指向的就是项目中xml文件的绝对路径。 44 | 45 | ```yml 46 | # mybatis xml文件热加载配置 47 | mybatis-xml-reload: 48 | # 是否开启 xml 热更新,true开启,false不开启,默认为false 49 | enabled: true 50 | # xml文件路径,可以填写多个,逗号分隔。如果想将xml文件放在指定目录而不是jar包内,可以用file前缀指定本地目录,例如 file:/c/mapper/*.xml 51 | # eg: `classpath:mapper/**/*Mapper.xml,file:/c/mapper/*.xml` 52 | mapper-locations: classpath:mapper/*Mapper.xml 53 | ``` 54 | # 学习交流 55 | > 如果有任何问题,欢迎提交Issue或加我微信告知,方便互相交流反馈~ 💘。最后,喜欢的话麻烦给我个star 56 | 57 | 关注公众号:程序员wayn,每周更新最新技术文章。回复关键字: 58 | - **学习**:加群交流,群内问题都会一一解答。 59 | - **开源项目**:获取博主自己写的三个开源项目,包含PC、H5商城、后台权限管理系统等。 60 | 61 | 62 | -------------------------------------------------------------------------------- /images/wx-mp-code.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wayn111/mybatis-xmlreload-spring-boot-starter/cd25511d48a60d1859c9bf9c6d664666e26972ba/images/wx-mp-code.png -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | jar 6 | io.github.wayn111 7 | mybatis-xmlreload-spring-boot-starter 8 | 3.0.5.m3 9 | mybatis-xmlreload-spring-boot-starter 10 | https://github.com/wayn111/mybatis-xmlreload-spring-boot-starter 11 | mybais springboot项目中xml文件热加载支持 12 | 13 | 14 | 15 | The Apache License, Version 2.0 16 | http://www.apache.org/licenses/LICENSE-2.0.txt 17 | 18 | 19 | 20 | https://github.com/wayn111/mybatis-xmlreload-spring-boot-starter 21 | https://github.com/wayn111/mybatis-xmlreload-spring-boot-starter.git 22 | 23 | 24 | 25 | 26 | wayn 27 | io.github.wayn111 28 | https://github.com/wayn111 29 | 1669738430@qq.com 30 | 31 | 32 | 33 | 34 | UTF-8 35 | UTF-8 36 | 8 37 | 38 | 3.0.1 39 | 0.18.0 40 | -Djdk.attach.allowAttachSelf --add-opens java.base/java.lang=ALL-UNNAMED -Dfile.encoding=UTF-8 41 | 42 | true 43 | UTF-8 44 | UTF-8 45 | 46 | ossrh 47 | https://s01.oss.sonatype.org/service/local/staging/deploy/maven2/ 48 | https://s01.oss.sonatype.org/content/repositories/snapshots/ 49 | 50 | 51 | 52 | 53 | 54 | 55 | org.springframework.boot 56 | spring-boot-dependencies 57 | 3.0.4 58 | pom 59 | import 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | org.springframework.boot 68 | spring-boot-autoconfigure 69 | compile 70 | 71 | 72 | org.springframework.boot 73 | spring-boot-autoconfigure-processor 74 | 75 | 76 | org.springframework.boot 77 | spring-boot-configuration-processor 78 | 79 | 80 | org.mybatis.spring.boot 81 | mybatis-spring-boot-starter 82 | ${mybatis-spring-boot-starter.version} 83 | 84 | 85 | 86 | io.methvin 87 | directory-watcher 88 | ${directory-watcher.version} 89 | 90 | 91 | 92 | 93 | 94 | 95 | ${deplay.id} 96 | ${deplay.snapshotRepository} 97 | 98 | 99 | ${deplay.id} 100 | ${deplay.repository} 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | org.springframework.boot 109 | spring-boot-maven-plugin 110 | 111 | 112 | org.apache.maven.plugins 113 | maven-compiler-plugin 114 | 115 | ${java.version} 116 | ${java.version} 117 | -parameters 118 | 119 | 120 | 121 | org.sonatype.plugins 122 | nexus-staging-maven-plugin 123 | 1.6.7 124 | true 125 | 126 | ossrh 127 | https://s01.oss.sonatype.org/ 128 | true 129 | 130 | 131 | 132 | org.apache.maven.plugins 133 | maven-source-plugin 134 | 2.2.1 135 | 136 | 137 | attach-sources 138 | 139 | jar-no-fork 140 | 141 | 142 | 143 | 144 | 145 | org.apache.maven.plugins 146 | maven-javadoc-plugin 147 | 2.9.1 148 | 149 | 150 | attach-javadocs 151 | 152 | jar 153 | 154 | 155 | -Xdoclint:none 156 | 157 | 158 | 159 | 160 | 170 | 171 | org.apache.maven.plugins 172 | maven-gpg-plugin 173 | 1.5 174 | 175 | 176 | sign-artifacts 177 | verify 178 | 179 | sign 180 | 181 | 182 | 183 | 184 | 185 | org.apache.maven.plugins 186 | maven-resources-plugin 187 | 2.6 188 | 189 | 190 | 191 | 192 | -------------------------------------------------------------------------------- /src/main/java/io/github/wayn111/mybatis/xmlreload/MybatisXmlReload.java: -------------------------------------------------------------------------------- 1 | package io.github.wayn111.mybatis.xmlreload; 2 | 3 | import io.github.wayn111.mybatis.xmlreload.autoconfiguration.MybatisXmlReloadProperties; 4 | import io.methvin.watcher.DirectoryWatcher; 5 | import org.apache.ibatis.builder.xml.XMLMapperBuilder; 6 | import org.apache.ibatis.builder.xml.XMLMapperEntityResolver; 7 | import org.apache.ibatis.mapping.MappedStatement; 8 | import org.apache.ibatis.mapping.ResultMap; 9 | import org.apache.ibatis.parsing.XNode; 10 | import org.apache.ibatis.parsing.XPathParser; 11 | import org.apache.ibatis.session.Configuration; 12 | import org.apache.ibatis.session.SqlSessionFactory; 13 | import org.slf4j.Logger; 14 | import org.slf4j.LoggerFactory; 15 | import org.springframework.core.io.FileSystemResource; 16 | import org.springframework.core.io.Resource; 17 | import org.springframework.core.io.support.PathMatchingResourcePatternResolver; 18 | 19 | import java.io.File; 20 | import java.io.IOException; 21 | import java.lang.reflect.Field; 22 | import java.nio.file.Path; 23 | import java.nio.file.Paths; 24 | import java.util.*; 25 | import java.util.concurrent.ScheduledThreadPoolExecutor; 26 | import java.util.concurrent.ThreadFactory; 27 | import java.util.stream.Collectors; 28 | import java.util.stream.Stream; 29 | 30 | /** 31 | * mybatis-xml-reload核心xml热加载逻辑 32 | */ 33 | public class MybatisXmlReload { 34 | 35 | private static final Logger logger = LoggerFactory.getLogger(MybatisXmlReload.class); 36 | 37 | 38 | private MybatisXmlReloadProperties prop; 39 | private List sqlSessionFactories; 40 | 41 | public MybatisXmlReload(MybatisXmlReloadProperties prop, List sqlSessionFactories) { 42 | this.prop = prop; 43 | this.sqlSessionFactories = sqlSessionFactories; 44 | } 45 | 46 | public void xmlReload() throws IOException { 47 | PathMatchingResourcePatternResolver patternResolver = new PathMatchingResourcePatternResolver(); 48 | String class_path_target_dir = File.separator + "target" + File.separator + "classes"; 49 | String maven_resources_dir = "/src/main/resources"; 50 | String maven_java_dir = "/src/main/java"; 51 | 52 | List mapperLocationsTmp = Stream.of(Optional.of(prop.getMapperLocations()).orElse(new String[0])) 53 | .flatMap(location -> Stream.of(getResources(patternResolver, location))).collect(Collectors.toList()); 54 | 55 | List mapperLocations = new ArrayList<>(mapperLocationsTmp.size() * 2); 56 | Set locationPatternSet = new HashSet<>(); 57 | for (Resource mapperLocation : mapperLocationsTmp) { 58 | // mapperLocations.add(mapperLocation); 59 | // 判断xml文件存放位置,只读取文件类型的xml文件,jar里的xml文件不做读取 60 | if (mapperLocation.isFile()) { 61 | mapperLocation.getFile(); 62 | String absolutePath = mapperLocation.getFile().getAbsolutePath(); 63 | // 先从maven_resources_dir目录下找xml文件目录,不存在就去maven_java_dir下找xml文件目录,都找不到就只能取target目录下xml文件目录 64 | File tmpFile = new File(absolutePath.replace(class_path_target_dir, maven_resources_dir)); 65 | if (!tmpFile.exists()) { 66 | tmpFile = new File(absolutePath.replace(class_path_target_dir, maven_java_dir)); 67 | } 68 | if (tmpFile.exists()) { 69 | locationPatternSet.add(Paths.get(tmpFile.getParent())); 70 | FileSystemResource fileSystemResource = new FileSystemResource(tmpFile); 71 | if (!mapperLocations.contains(fileSystemResource)) { 72 | mapperLocations.add(fileSystemResource); 73 | } 74 | } else { 75 | locationPatternSet.add(Paths.get(mapperLocation.getFile().getParent())); 76 | } 77 | } 78 | } 79 | 80 | List rootPaths = new ArrayList<>(locationPatternSet); 81 | DirectoryWatcher watcher = DirectoryWatcher.builder() 82 | .paths(rootPaths) // or use paths(directoriesToWatch) 83 | .listener(event -> { 84 | switch (event.eventType()) { 85 | case CREATE: /* file created */ 86 | break; 87 | case MODIFY: /* file modified */ 88 | Path modifyPath = event.path(); 89 | String absolutePath = modifyPath.toFile().getAbsolutePath(); 90 | if (!new File(absolutePath).exists()) { 91 | break; 92 | } 93 | logger.info("mybatis xml file has changed: '{}'", absolutePath); 94 | for (SqlSessionFactory sqlSessionFactory : sqlSessionFactories) { 95 | try { 96 | Configuration targetConfiguration = sqlSessionFactory.getConfiguration(); 97 | Class tClass = targetConfiguration.getClass(), aClass = targetConfiguration.getClass(); 98 | if (targetConfiguration.getClass().getSimpleName().equals("MybatisConfiguration")) { 99 | aClass = Configuration.class; 100 | } 101 | Set loadedResources = (Set) getFieldValue(targetConfiguration, aClass, "loadedResources"); 102 | loadedResources.clear(); 103 | 104 | Map resultMaps = (Map) getFieldValue(targetConfiguration, tClass, "resultMaps"); 105 | Map sqlFragmentsMaps = (Map) getFieldValue(targetConfiguration, tClass, "sqlFragments"); 106 | Map mappedStatementMaps = (Map) getFieldValue(targetConfiguration, tClass, "mappedStatements"); 107 | 108 | for (Resource mapperLocation : mapperLocations) { 109 | if (!mapperLocation.isFile()) { 110 | continue; 111 | } 112 | if (!absolutePath.equals(mapperLocation.getFile().getAbsolutePath())) { 113 | continue; 114 | } 115 | XPathParser parser = null; 116 | try { 117 | parser = new XPathParser(mapperLocation.getInputStream(), true, targetConfiguration.getVariables(), new XMLMapperEntityResolver()); 118 | } catch (Exception e) { 119 | } 120 | XNode mapperXnode = parser.evalNode("/mapper"); 121 | List resultMapNodes = mapperXnode.evalNodes("/mapper/resultMap"); 122 | String namespace = mapperXnode.getStringAttribute("namespace"); 123 | for (XNode xNode : resultMapNodes) { 124 | String id = xNode.getStringAttribute("id", xNode.getValueBasedIdentifier()); 125 | Iterator> iterator = resultMaps.entrySet().iterator(); 126 | while (iterator.hasNext()) { 127 | Map.Entry next = iterator.next(); 128 | String key = next.getKey(); 129 | if (key.contains(namespace + "." + id)) { 130 | iterator.remove(); 131 | } 132 | // 处理 association、collection标签 133 | if (key.contains(namespace + ".mapper_resultMap")) { 134 | iterator.remove(); 135 | } 136 | } 137 | } 138 | 139 | List sqlNodes = mapperXnode.evalNodes("/mapper/sql"); 140 | for (XNode sqlNode : sqlNodes) { 141 | String id = sqlNode.getStringAttribute("id", sqlNode.getValueBasedIdentifier()); 142 | sqlFragmentsMaps.remove(namespace + "." + id); 143 | } 144 | 145 | List msNodes = mapperXnode.evalNodes("select|insert|update|delete"); 146 | for (XNode msNode : msNodes) { 147 | String id = msNode.getStringAttribute("id", msNode.getValueBasedIdentifier()); 148 | mappedStatementMaps.remove(namespace + "." + id); 149 | } 150 | try { 151 | XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(mapperLocation.getInputStream(), 152 | targetConfiguration, mapperLocation.toString(), targetConfiguration.getSqlFragments()); 153 | xmlMapperBuilder.parse(); 154 | } catch (Exception e) { 155 | logger.error(e.getMessage(), e); 156 | } 157 | logger.info("mapperLocation reload success: '{}'", mapperLocation); 158 | } 159 | } catch (Exception e) { 160 | logger.error(e.getMessage(), e); 161 | } 162 | } 163 | break; 164 | case DELETE: /* file deleted */ 165 | break; 166 | } 167 | }) 168 | // .fileHashing(false) // defaults to true 169 | // .logger(logger) // defaults to LoggerFactory.getLogger(DirectoryWatcher.class) 170 | // .watchService(watchService) // defaults based on OS to either JVM WatchService or the JNA macOS WatchService 171 | .build(); 172 | ThreadFactory threadFactory = r -> { 173 | Thread thread = new Thread(r); 174 | thread.setName("xml-reload"); 175 | thread.setDaemon(true); 176 | return thread; 177 | }; 178 | watcher.watchAsync(new ScheduledThreadPoolExecutor(1, threadFactory)); 179 | 180 | } 181 | 182 | /** 183 | * 根据xml路径获取对应实际文件 184 | * 185 | * @param location 文件位置 186 | * @return Resource[] 187 | */ 188 | private Resource[] getResources(PathMatchingResourcePatternResolver patternResolver, String location) { 189 | try { 190 | return patternResolver.getResources(location); 191 | } catch (IOException e) { 192 | return new Resource[0]; 193 | } 194 | } 195 | 196 | /** 197 | * 根据反射获取Configuration对象中属性 198 | * 199 | * @param targetConfiguration 200 | * @param aClass 201 | * @param filed 202 | * @return 203 | * @throws NoSuchFieldException 204 | * @throws IllegalAccessException 205 | */ 206 | private static Object getFieldValue(Configuration targetConfiguration, Class aClass, 207 | String filed) throws NoSuchFieldException, IllegalAccessException { 208 | Field resultMapsField = aClass.getDeclaredField(filed); 209 | resultMapsField.setAccessible(true); 210 | return resultMapsField.get(targetConfiguration); 211 | } 212 | } 213 | -------------------------------------------------------------------------------- /src/main/java/io/github/wayn111/mybatis/xmlreload/autoconfiguration/MybatisXmlReloadConfiguration.java: -------------------------------------------------------------------------------- 1 | package io.github.wayn111.mybatis.xmlreload.autoconfiguration; 2 | 3 | import io.github.wayn111.mybatis.xmlreload.MybatisXmlReload; 4 | import org.apache.ibatis.session.SqlSessionFactory; 5 | import org.springframework.boot.LazyInitializationExcludeFilter; 6 | import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; 7 | import org.springframework.boot.context.properties.EnableConfigurationProperties; 8 | import org.springframework.context.annotation.Bean; 9 | import org.springframework.context.annotation.Configuration; 10 | 11 | import java.io.IOException; 12 | import java.util.List; 13 | 14 | /** 15 | * mybatis xml热加载自动配置 16 | * 17 | * @author wayn 18 | */ 19 | @Configuration 20 | @EnableConfigurationProperties({MybatisXmlReloadProperties.class}) 21 | public class MybatisXmlReloadConfiguration { 22 | 23 | @Bean 24 | @ConditionalOnMissingBean 25 | public MybatisXmlReload mybatisXmlReload(MybatisXmlReloadProperties prop, 26 | List sqlSessionFactories) throws IOException { 27 | MybatisXmlReload mybatisXmlReload = new MybatisXmlReload(prop, sqlSessionFactories); 28 | if (prop.getEnabled()) { 29 | mybatisXmlReload.xmlReload(); 30 | } 31 | return mybatisXmlReload; 32 | } 33 | 34 | @Bean 35 | public static LazyInitializationExcludeFilter integrationLazyInitializationExcludeFilter() { 36 | return LazyInitializationExcludeFilter.forBeanTypes(MybatisXmlReload.class); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/io/github/wayn111/mybatis/xmlreload/autoconfiguration/MybatisXmlReloadProperties.java: -------------------------------------------------------------------------------- 1 | package io.github.wayn111.mybatis.xmlreload.autoconfiguration; 2 | 3 | import org.springframework.boot.context.properties.ConfigurationProperties; 4 | 5 | /** 6 | * mybatis-xml-reload配置属性类 7 | */ 8 | @ConfigurationProperties(prefix = "mybatis-xml-reload") 9 | public class MybatisXmlReloadProperties { 10 | private boolean enabled; 11 | 12 | private String[] mapperLocations; 13 | 14 | public boolean getEnabled() { 15 | return enabled; 16 | } 17 | 18 | public void setEnabled(boolean enabled) { 19 | this.enabled = enabled; 20 | } 21 | 22 | public String[] getMapperLocations() { 23 | return mapperLocations; 24 | } 25 | 26 | public void setMapperLocations(String[] mapperLocations) { 27 | this.mapperLocations = mapperLocations; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/main/resources/META-INF/additional-spring-configuration-metadata.json: -------------------------------------------------------------------------------- 1 | { 2 | "properties": [ 3 | { 4 | "defaultValue": true, 5 | "name": "mybatis-xml-reload.enabled", 6 | "description": "if mybatis.xml-reload.enabled is true, will enable xml hot reload configuration.", 7 | "type": "java.lang.Boolean" 8 | }, 9 | { 10 | "defaultValue": "", 11 | "name": "mybatis-xml-reload.mapper-locations", 12 | "description": "xml reload mapper locations, eg: classpath:mapper/*Mapper.xml, classpath:other/*Mapper.xml", 13 | "type": "java.lang.String" 14 | } 15 | ] 16 | } 17 | -------------------------------------------------------------------------------- /src/main/resources/META-INF/spring.factories: -------------------------------------------------------------------------------- 1 | org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ 2 | io.github.wayn111.mybatis.xmlreload.autoconfiguration.MybatisXmlReloadConfiguration 3 | -------------------------------------------------------------------------------- /src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports: -------------------------------------------------------------------------------- 1 | io.github.wayn111.mybatis.xmlreload.autoconfiguration.MybatisXmlReloadConfiguration 2 | --------------------------------------------------------------------------------