Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'

前端 未结 20 2458
予麋鹿
予麋鹿 2020-12-13 06:02

This is the Warning im getting in console, Im confused with this warning:

Loading class `com.mysql.jdbc.Driver\'. 
This is deprecated. The new driver class is         


        
20条回答
  •  悲&欢浪女
    2020-12-13 06:30

    The sentence "Loading class 'com.mysql.jdbc.Driver'. This is deprecated. The new driver class is 'com.mysql.cj.jdbc.Driver' " is clear. You should use the newer driver, like this:

    Class.forName("com.mysql.cj.jdbc.Driver");
    

    And in mysql-connector-java-8.0.17. You would find that Class com.mysql.jdbc.Driver doesn't provide service any more. (You also can found the warning came from here.)

    public class Driver extends com.mysql.cj.jdbc.Driver {
        public Driver() throws SQLException {
        }
    
        static {
            System.err.println("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.");
        }
    }
    

    The sentence 'The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.' It mean that write code like this is ok:

    //Class.forName("com.mysql.cj.jdbc.Driver");
    Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/world?useSSL=false&serverTimezone=Asia/Shanghai","root","root");
    

    Due to SPI, driver is automatically registered. How does it work? You can find this from java.sql.DriverManager:

    private static void ensureDriversInitialized() {
                              ...
        ServiceLoader loadedDrivers = ServiceLoader.load(Driver.class);
                              ...
    }
    

    And in your mysql-connector-java-XXX.jar, you also can find the file 'java.sql.Driver' in the META-INF\services. The file as follows:

    com.mysql.cj.jdbc.Driver
    

    When you run DriverManager.getConnection(), the static block also start running. So driver can be automatically registered with file 'java.sql.Driver'.

    And more about SPI -> Difference between SPI and API?.

提交回复
热议问题