Class.forName("com.mysql.jdbc.Driver")理解

场景:
    为了理解操作jdbc时需要先使用Class.forName("com.mysql.jdbc.Driver")这行代码的作用。
解析:
    1.使用Class.forName("com.mysql.jdbc.Driver")后,jvm会加载这个类
    2.加载这个类后,进入com.mysql.jdbc.Driver,会立即注册:

    
	// Register ourselves with the DriverManager
	static {
		try {
			java.sql.DriverManager.registerDriver(new Driver());
		} catch (SQLException E) {
			throw new RuntimeException("Can't register driver!");
		}
	}

3.进入java.sql.DriverManager,DriverManager管理器会调用注册方法,并把Driver放入registeredDrivers列表中:

 public static synchronized void registerDriver(java.sql.Driver driver)
        throws SQLException {

        /* Register the driver if it has not already been added to our list */
        if(driver != null) {
            registeredDrivers.addIfAbsent(new DriverInfo(driver));
        } else {
            // This is for compatibility with the original DriverManager
            throw new NullPointerException();
        }

        println("registerDriver: " + driver);

    }

 以上代码,registeredDrivers是如下类型

private final static CopyOnWriteArrayList<DriverInfo> registeredDrivers = new CopyOnWriteArrayList<DriverInfo>();

4.在自己代码中,调用DriverManager.getConnection获取连接时,如下:

    @CallerSensitive
    public static Connection getConnection(String url,
        String user, String password) throws SQLException {
        java.util.Properties info = new java.util.Properties();

        if (user != null) {
            info.put("user", user);
        }
        if (password != null) {
            info.put("password", password);
        }

        return (getConnection(url, info, Reflection.getCallerClass()));
    }

   5.进入内部的getConnection(url, info, Reflection.getCallerClass())

private static Connection getConnection(
        String url, java.util.Properties info, Class<?> caller) throws SQLException {
        /*
         * When callerCl is null, we should check the application's
         * (which is invoking this class indirectly)
         * classloader, so that the JDBC driver class outside rt.jar
         * can be loaded from here.
         */
        ClassLoader callerCL = caller != null ? caller.getClassLoader() : null;
        synchronized (DriverManager.class) {
            // synchronize loading of the correct classloader.
            if (callerCL == null) {
                callerCL = Thread.currentThread().getContextClassLoader();
            }
        }

        if(url == null) {
            throw new SQLException("The url cannot be null", "08001");
        }

        println("DriverManager.getConnection(\"" + url + "\")");

        // Walk through the loaded registeredDrivers attempting to make a connection.
        // Remember the first exception that gets raised so we can reraise it.
        SQLException reason = null;

        for(DriverInfo aDriver : registeredDrivers) {
            // If the caller does not have permission to load the driver then
            // skip it.
            if(isDriverAllowed(aDriver.driver, callerCL)) {
                try {
                    println("    trying " + aDriver.driver.getClass().getName());
                    Connection con = aDriver.driver.connect(url, info);
                    if (con != null) {
                        // Success!
                        println("getConnection returning " + aDriver.driver.getClass().getName());
                        return (con);
                    }
                } catch (SQLException ex) {
                    if (reason == null) {
                        reason = ex;
                    }
                }

            } else {
                println("    skipping: " + aDriver.getClass().getName());
            }

        }

        // if we got here nobody could connect.
        if (reason != null)    {
            println("getConnection failed: " + reason);
            throw reason;
        }

        println("getConnection: no suitable driver found for "+ url);
        throw new SQLException("No suitable driver found for "+ url, "08001");
    }
}

6.以上代码会去遍历一个列表,registeredDrivers列表里即是注册过的所有驱动
7.在getConnection(url, info, Reflection.getCallerClass())内部遍历registeredDrivers, 取出每个驱动进行判断即进入isDriverAllowed(aDriver.driver, callerCL)判断

private static boolean isDriverAllowed(Driver driver, ClassLoader classLoader) {
        boolean result = false;
        if(driver != null) {
            Class<?> aClass = null;
            try {
                aClass =  Class.forName(driver.getClass().getName(), true, classLoader);
            } catch (Exception ex) {
                result = false;
            }

             result = ( aClass == driver.getClass() ) ? true : false;
        }

        return result;
    }

 以上,所有注册驱动是否都一一匹配,都有即返回true.
8.以上都为true的话,依次执行如下代码
      Connection con = aDriver.driver.connect(url, info);
      如果连接成功,则返回con,没成功就继续遍历
 9.找不到不为null的Connection时,就抛出找不到合适驱动
      即可No suitable driver found ......

结论:只有com.mysql.jdbc.Driver提前被加载,在驱动管理器DriverManager获取连接时候才能正常验证通过,并创建连接.

以上,TKS.

猜你喜欢

转载自blog.csdn.net/zhangbeizhen18/article/details/86500087