JDBC驱动加载


try
        {
            Class.forName("com.mysql.jdbc.Driver");
            Class.forName("oracle.jdbc.driver.OracleDriver");
        }
        catch (ClassNotFoundException e)
        {
            logger.error("driver not exists.", e);
        }

  1. 当注册了多个driver时,下面的代码到底是怎么选择driver的呢?
    Connection connection = DriverManager.getConnection(url, user, pwd);
    首先,class.forName("xxx“)触发Driver实现类的加载时,Driver实现的static块会向DriverManager注册该Driver。
    比如:mysql 的diver是这样的:
public class Driver extends NonRegisteringDriver implements java.sql.Driver {
    public Driver() throws SQLException {
    }

    static {
        try {
            DriverManager.registerDriver(new Driver());
        } catch (SQLException var1) {
            throw new RuntimeException("Can't register driver!");
        }
    }
}

然后DriverManager会一个一个驱动去试,哪个驱动能连接上数据库就使用那个驱动:

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.
         */
        //caller的类加载器优先
        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");
    }


}
  1. 类权限判断
    DriverManager先通过isDriverAllowed(aDriver.driver, callerCL)判断调用方(通过Connection connection = DriverManager.getConnection(url, user, pwd);获取连接的业务代码)的加载器在加载Driver实现类(通过名字)之后的直接类加载器是否等于已注册Driver类的类加载器,如果相等,才尝试去connect。
    这么做一方面能保证Driver实现类在整个系统不会出现被多个classLoader直接加载,也就是只有一个namespace,另一方面也防止了业务代码执行Connection connection = DriverManager.getConnection(url, user, pwd);时出现ClassNotFound。
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。