com.mysql.cj.jdbc.Driver 警告

今天跑 shenyu 项目的时候出现一个十分显眼的报错

2022-05-03 21:55:08 [main] INFO  org.apache.shenyu.admin.spring.LocalDataSourceLoader - execute shenyu schema sql: sql-script/mysql/schema.sql
Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
2022-05-03 21:55:09 [main] INFO  com.zaxxer.hikari.HikariDataSource - HikariPool-1 - Starting...

着重拎出来看看

Loading class com.mysql.jdbc.Driver'. This is deprecated. The new driver class iscom.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.

大概意思就是警告你要换个类名,但是项目代码运行并没有错误
我这里 mysql-server 版本是 8.0.29, mysql-connector-java 版本是 8.0.16


解决这个报错的问题很简单就是替换一下配置的 driver class 名字

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/shenyu25?useUnicode=true&characterEncoding=utf-8&useSSL=false&allowPublicKeyRetrieval=true
    username: root
    password: febsA123
    #替换前   driver-class-name: com.mysql.jdbc.Driver
    driver-class-name: com.mysql.cj.jdbc.Driver

好奇查下原因
官网文档在 8.0 的连接介绍里确实有介绍要这么用
https://dev.mysql.com/doc/connector-j/8.0/en/connector-j-usagenotes-connect-drivermanager.html

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

// Notice, do not import com.mysql.cj.jdbc.*
// or you will have problems!

public class LoadDriver {
    public static void main(String[] args) {
        try {
            // The newInstance() call is a work around for some
            // broken Java implementations

            Class.forName("com.mysql.cj.jdbc.Driver").newInstance();
        } catch (Exception ex) {
            // handle the error
        }
    }
}

切换到 5.1 的页面名字就不一样了
https://dev.mysql.com/doc/connector-j/5.1/en/connector-j-usagenotes-connect-drivermanager.html

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

// Notice, do not import com.mysql.jdbc.*
// or you will have problems!

public class LoadDriver {
    public static void main(String[] args) {
        try {
            // The newInstance() call is a work around for some
            // broken Java implementations

            Class.forName("com.mysql.jdbc.Driver").newInstance();
        } catch (Exception ex) {
            // handle the error
        }
    }
}

翻了下依赖包下面的源码就发现警告信息出处了


Driver.java

这里也可以看到为了兼容原来的使用方式把
com.mysql.jdbc.Driver 实现成了 com.mysql.cj.jdbc.Driver 的子类

好家伙

你可能感兴趣的:(com.mysql.cj.jdbc.Driver 警告)