錯誤:
在配置 Spring Boot 的 Mybatis 的代碼自動生成文件時出現了如下錯誤:
錯誤日志:
1 java.lang.RuntimeException: Cannot instantiate object of type tk.mybatis.generator.MapperPlugin 2 at org.mybatis.generator.internal.ObjectFactory.createInternalObject(ObjectFactory.java:182) 3 at org.mybatis.generator.internal.ObjectFactory.createPlugin(ObjectFactory.java:219) 4 at org.mybatis.generator.config.Context.generateFiles(Context.java:500) 5 at org.mybatis.generator.api.MyBatisGenerator.generate(MyBatisGenerator.java:269) 6 at org.mybatis.generator.api.MyBatisGenerator.generate(MyBatisGenerator.java:139) 7 at com.weChat.MybatisStartup.GeneratorDisplay.generator(GeneratorDisplay.java:33) 8 at com.weChat.MybatisStartup.GeneratorDisplay.main(GeneratorDisplay.java:17) 9 Caused by: java.lang.ClassNotFoundException: tk.mybatis.generator.MapperPlugin 10 at java.net.URLClassLoader.findClass(URLClassLoader.java:381) 11 at java.lang.ClassLoader.loadClass(ClassLoader.java:424) 12 at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349) 13 at java.lang.ClassLoader.loadClass(ClassLoader.java:357) 14 at java.lang.Class.forName0(Native Method) 15 at java.lang.Class.forName(Class.java:348) 16 at org.mybatis.generator.internal.ObjectFactory.internalClassForName(ObjectFactory.java:148) 17 at org.mybatis.generator.internal.ObjectFactory.createInternalObject(ObjectFactory.java:178) 18 ... 6 more
原因及其解決辦法:
導致這種問題的原因不多,主要分為兩種:
- 在代碼自動生成配置文件中的依賴引用(
<plugin type="tk.mybatis.mapper.generator.MapperPlugin">
)的 Type 值寫的有問題(我的就是這個問題),這個值一定要對應正確,否者系統是找不到相應的文件; - pom.xml 文件中的依賴沒有或者說沒有依賴成功,如果沒有對應的依賴或者沒有引用成功,那么也就不可能有后續的在配置文件中的引用了,我的依賴引用的代碼如下,若是在pom.xml文件中存在相應的依賴的代碼的話,那就是沒有依賴成功,可以查看對應的依賴包中(或者maven庫中)是否有對應的jar包,如果有對應的jar包,那么就是版本的不兼容,修改 tk.mybatis 和 generator的版本號,嘗試幾次就差不多可以了。
1 <!-- 我的相關本地依賴代碼(另:我的Spring Boot版本是 [v2.1.5.RELEASE]的 )--> 2 3 <!-- mybatis 反向自動生成依賴 --> 4 <dependency> 5 <groupId>org.mybatis.generator</groupId> 6 <artifactId>mybatis-generator-core</artifactId> 7 <version>1.3.7</version> 8 </dependency> 9 10 <!-- https://mvnrepository.com/artifact/tk.mybatis/mapper --> 11 <dependency> 12 <groupId>tk.mybatis</groupId> 13 <artifactId>mapper</artifactId> 14 <version>4.1.5</version> 15 </dependency>