Mybatis源码报错java.lang.ClassNotFoundException: Cannot find class: com.mysql.jdbc.Driver
在阅读mysql源码的时候,下载下来源码,写了一个简单demo,运行,报错
java.sql.SQLException: Error setting driver on UnpooledDataSource. Cause: java.lang.ClassNotFoundException: Cannot find class: com.mysql.jdbc.Driver at org.apache.ibatis.exceptions.ExceptionFactory.wrapException(ExceptionFactory.java:30) at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:153) at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:145) at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:140) at org.apache.ibatis.session.defaults.DefaultSqlSession.selectOne(DefaultSqlSession.java:76) at org.apache.ibatis.demo.MybatisMain.main(MybatisMain.java:36) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
网上查了一下,大部分千篇一律都是mysql-connector-java-x.x.x-bin.jar的问题,但是不论我引入什么版本的包,问题依然存在。
经过一步步调试,发现加载com.mysql.jdbc.Driver类的地方是org.apache.ibatis.io.ClassLoaderWapper的如下方法
Class<?> classForName(String name, ClassLoader[] classLoader) throws ClassNotFoundException { for (ClassLoader cl : classLoader) { if (null != cl) { try { return Class.forName(name, true, cl); } catch (ClassNotFoundException e) { // we'll ignore this until all classloaders fail to locate the class } } } throw new ClassNotFoundException("Cannot find class: " + name); }
但是为什么加载不了呢?
于是,在main方法中测试一下
public class MybatisMain { public static void main(String[] args) throws IOException { try { Class.forName("com.mysql.jdbc.Driver", true, Thread.currentThread().getContextClassLoader()); } catch (ClassNotFoundException e) { e.printStackTrace(); } } }
结果,仍然加载不了。
结论:
大家看pom文件
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.24</version> <scope>test</scope> </dependency>
注意到pom文件中<scope>test</scope>,问题就出在这,注释掉这一行,问题解决。