Mybatis源码报错java.lang.ClassNotFoundException: Cannot find class: com.mysql.jdbc.Driver

2021/12/3 2:36:07

本文主要是介绍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>,问题就出在这,注释掉这一行,问题解决。



这篇关于Mybatis源码报错java.lang.ClassNotFoundException: Cannot find class: com.mysql.jdbc.Driver的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程