JDBC 驱动加载过程
2012-11-01 21:51
323 查看
参见如下简单的程序
下面我们来分析 DriverManager 的这个方法:
查看一下DriverManager源码,代码块我按执行步骤全部贴出来:
1. 调用getConnection()方法
2. 调用实际起作用的getConnection()方法
这里有几个比较重要的地方,一个L25的initialize()方法,下面是他的源码
这一段就是加载数据库驱动的地方,以我用的connector/j为例,看L27,这个DriverService是一个内部类,代码如下:
L11的 sun.misc.Service.providers()方法是关键所在,代码如下
好了。经过各种进入,终于到达了目的地,上面这段代码就是加载数据库驱动的所在,请看LazyIterator里的从L57开始的这一段
实际上很简单,他就是去CLASSPATH里的library里找 META-INF/services/java.sql.Driver 这个文件,其中 java.sql.Driver 这个名字是通过上面的 service.getName()获得的。 数据库驱动的类里都会有 META-INF 这个文件夹,我们可以MySQL的connector/j数据库驱动加到环境变量里后自己尝试一下输出,代码如下
控制台会输出
看到了吗,这两个jar文件一个是jdk自带的,另一个是我们自己加到环境变量里的mysql驱动,然后我们再看看这两个java.sql.Driver里的东西,他们分别是
自此,我们终于找到了我们需要加载的两个数据库驱动类的名称。然后再看LazyItarator里的next方法,注意到里面的forName了吧,这个方法就是加载类信息。顺便提一下,实际上forName方法里也是调用的ClassLoader的loadClass()方法来加载类信息的。
这里还有一步很关键的,就是加载类信息的时候发生了什么。我们看看 com.mysql.jdbc.Driver 的源码
注意到这个static语句块了吧。就是这段代码,把自己注册到了DriverManager的driverlist里。
终于结束了,当所有驱动程序的Driver实例注册完毕,DriverManager就开始遍历这些注册好的驱动,对传入的数据库链接DSN调用这些驱动的connect方法,最后返回一个对应的数据库驱动类里的connect方法返回的java.sql.Connection实例,也就是我最开始那段测试代码里的conn。大家可以返回去看看DriverManager在initialize()结束后干了什么就明白
最后总结一下流程:
1. 调用 getConnection 方法
2. DriverManager 通过 SystemProerty jdbc.driver 获取数据库驱动类名
或者
通过ClassLoader.getSystemResources 去CLASSPATH里的类信息里查找 META-INF/services/java.sql.Driver 这个文件里查找获取数据库驱动名
3. 通过找的的driver名对他们进行类加载
4. Driver类在被加载的时候执行static语句块,将自己注册到DriverManager里去
5. 注册完毕后 DriverManager 调用这些驱动的connect方法,将合适的Connection 返回给客户端
package db; import java.sql.*; public class DBTest { private static final String USERNAME = "root"; private static final String PASSWD = "root"; private static final String DATABASE = "test"; private static final String DBMS = "mysql"; private static final String HOST = "localhost"; private static final String PORT = "3306"; private static final String DSN = "jdbc:" + DBMS + "://" + HOST + ":" + PORT + "/" + DATABASE; public static void main(String[] args) { try { Connection conn = DriverManager.getConnection(DSN, USERNAME, PASSWD); String query = "SELECT * FROM user"; Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(query); while (rs.next()) { System.out.println(rs.getInt(1) + " " + rs.getString(2) + " " + rs.getInt(3)); } } catch (SQLException e) { e.printStackTrace(); } } }
下面我们来分析 DriverManager 的这个方法:
public static Connection getConnection(String url, String user, String password) throws SQLException
查看一下DriverManager源码,代码块我按执行步骤全部贴出来:
1. 调用getConnection()方法
/** * Attempts to establish a connection to the given database URL. * The <code>DriverManager</code> attempts to select an appropriate driver from * the set of registered JDBC drivers. * * @param url a database url of the form * <code>jdbc:<em>subprotocol</em>:<em>subname</em></code> * @param user the database user on whose behalf the connection is being * made * @param password the user's password * @return a connection to the URL * @exception SQLException if a database access error occurs */ public static Connection getConnection(String url, String user, String password) throws SQLException { java.util.Properties info = new java.util.Properties(); // Gets the classloader of the code that called this method, may // be null. ClassLoader callerCL = DriverManager.getCallerClassLoader(); if (user != null) { info.put("user", user); } if (password != null) { info.put("password", password); } return (getConnection(url, info, callerCL)); }
2. 调用实际起作用的getConnection()方法
// Worker method called by the public getConnection() methods. private static Connection getConnection( String url, java.util.Properties info, ClassLoader callerCL) throws SQLException { java.util.Vector drivers = null; /* * 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. */ 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 + "\")"); if (!initialized) { initialize(); } synchronized (DriverManager.class){ // use the readcopy of drivers drivers = readDrivers; } // Walk through the loaded drivers attempting to make a connection. // Remember the first exception that gets raised so we can reraise it. SQLException reason = null; for (int i = 0; i < drivers.size(); i++) { DriverInfo di = (DriverInfo)drivers.elementAt(i); // If the caller does not have permission to load the driver then // skip it. if ( getCallerClass(callerCL, di.driverClassName ) != di.driverClass ) { println(" skipping: " + di); continue; } try { println(" trying " + di); Connection result = di.driver.connect(url, info); if (result != null) { // Success! println("getConnection returning " + di); return (result); } } catch (SQLException ex) { if (reason == null) { reason = ex; } } } // 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"); }
这里有几个比较重要的地方,一个L25的initialize()方法,下面是他的源码
// Class initialization. static void initialize() { if (initialized) { return; } initialized = true; loadInitialDrivers(); println("JDBC DriverManager initialized"); } private static void loadInitialDrivers() { String drivers; try { drivers = (String) java.security.AccessController.doPrivileged( new sun.security.action.GetPropertyAction("jdbc.drivers")); } catch (Exception ex) { drivers = null; } // If the driver is packaged as a Service Provider, // load it. // Get all the drivers through the classloader // exposed as a java.sql.Driver.class service. DriverService ds = new DriverService(); // Have all the privileges to get all the // implementation of java.sql.Driver java.security.AccessController.doPrivileged(ds); println("DriverManager.initialize: jdbc.drivers = " + drivers); if (drivers == null) { return; } while (drivers.length() != 0) { int x = drivers.indexOf(':'); String driver; if (x < 0) { driver = drivers; drivers = ""; } else { driver = drivers.substring(0, x); drivers = drivers.substring(x+1); } if (driver.length() == 0) { continue; } try { println("DriverManager.Initialize: loading " + driver); Class.forName(driver, true, ClassLoader.getSystemClassLoader()); } catch (Exception ex) { println("DriverManager.Initialize: load failed: " + ex); } } }
这一段就是加载数据库驱动的地方,以我用的connector/j为例,看L27,这个DriverService是一个内部类,代码如下:
// DriverService is a package-private support class. class DriverService implements java.security.PrivilegedAction { Iterator ps = null; public DriverService() {}; public Object run() { // uncomment the followin line before mustang integration // Service s = Service.lookup(java.sql.Driver.class); // ps = s.iterator(); ps = Service.providers(java.sql.Driver.class); /* Load these drivers, so that they can be instantiated. * It may be the case that the driver class may not be there * i.e. there may be a packaged driver with the service class * as implementation of java.sql.Driver but the actual class * may be missing. In that case a sun.misc.ServiceConfigurationError * will be thrown at runtime by the VM trying to locate * and load the service. * * Adding a try catch block to catch those runtime errors * if driver not available in classpath but it's * packaged as service and that service is there in classpath. */ try { while (ps.hasNext()) { ps.next(); } // end while } catch(Throwable t) { // Do nothing } return null; } //end run } //end DriverService
L11的 sun.misc.Service.providers()方法是关键所在,代码如下
/** * Locates and incrementally instantiates the available providers of a * given service using the given class loader. * * <p> This method transforms the name of the given service class into a * provider-configuration filename as described above and then uses the * <tt>getResources</tt> method of the given class loader to find all * available files with that name. These files are then read and parsed to * produce a list of provider-class names. The iterator that is returned * uses the given class loader to lookup and then instantiate each element * of the list. * * <p> Because it is possible for extensions to be installed into a running * Java virtual machine, this method may return different results each time * it is invoked. <p> * * @param service * The service's abstract service class * * @param loader * The class loader to be used to load provider-configuration files * and instantiate provider classes, or <tt>null</tt> if the system * class loader (or, failing that the bootstrap class loader) is to * be used * * @return An <tt>Iterator</tt> that yields provider objects for the given * service, in some arbitrary order. The iterator will throw a * <tt>ServiceConfigurationError</tt> if a provider-configuration * file violates the specified format or if a provider class cannot * be found and instantiated. * * @throws ServiceConfigurationError * If a provider-configuration file violates the specified format * or names a provider class that cannot be found and instantiated * * @see #providers(java.lang.Class) * @see #installedProviders(java.lang.Class) */ public static Iterator providers(Class service, ClassLoader loader) throws ServiceConfigurationError { return new LazyIterator(service, loader); } /** * Private inner class implementing fully-lazy provider lookup */ private static class LazyIterator implements Iterator { Class service; ClassLoader loader; Enumeration configs = null; Iterator pending = null; Set returned = new TreeSet(); String nextName = null; private LazyIterator(Class service, ClassLoader loader) { this.service = service; this.loader = loader; } public boolean hasNext() throws ServiceConfigurationError { if (nextName != null) { return true; } if (configs == null) { try { String fullName = prefix + service.getName(); if (loader == null) configs = ClassLoader.getSystemResources(fullName); else configs = loader.getResources(fullName); } catch (IOException x) { fail(service, ": " + x); } } while ((pending == null) || !pending.hasNext()) { if (!configs.hasMoreElements()) { return false; } pending = parse(service, (URL)configs.nextElement(), returned); } nextName = (String)pending.next(); return true; } public Object next() throws ServiceConfigurationError { if (!hasNext()) { throw new NoSuchElementException(); } String cn = nextName; nextName = null; try { return Class.forName(cn, true, loader).newInstance(); } catch (ClassNotFoundException x) { fail(service, "Provider " + cn + " not found"); } catch (Exception x) { fail(service, "Provider " + cn + " could not be instantiated: " + x, x); } return null; /* This cannot happen */ } public void remove() { throw new UnsupportedOperationException(); } }
好了。经过各种进入,终于到达了目的地,上面这段代码就是加载数据库驱动的所在,请看LazyIterator里的从L57开始的这一段
实际上很简单,他就是去CLASSPATH里的library里找 META-INF/services/java.sql.Driver 这个文件,其中 java.sql.Driver 这个名字是通过上面的 service.getName()获得的。 数据库驱动的类里都会有 META-INF 这个文件夹,我们可以MySQL的connector/j数据库驱动加到环境变量里后自己尝试一下输出,代码如下
package test; import java.io.IOException; import java.net.URL; import java.sql.Driver; import java.util.Enumeration; public class Test { public static void main(String[] args) throws IOException { Enumeration<URL> list = ClassLoader.getSystemResources("META-INF/services/" + Driver.class.getName()); while (list.hasMoreElements()) { System.out.println(list.nextElement()); } } }
控制台会输出
jar:file:/usr/local/glassfish3/jdk7/jre/lib/resources.jar!/META-INF/services/java.sql.Driver jar:file:/home/alexis/mysql-connector/mysql-connector-java-5.1.22-bin.jar!/META-INF/services/java.sql.Driver
看到了吗,这两个jar文件一个是jdk自带的,另一个是我们自己加到环境变量里的mysql驱动,然后我们再看看这两个java.sql.Driver里的东西,他们分别是
sun.jdbc.odbc.JdbcOdbcDriver com.mysql.jdbc.Driver
自此,我们终于找到了我们需要加载的两个数据库驱动类的名称。然后再看LazyItarator里的next方法,注意到里面的forName了吧,这个方法就是加载类信息。顺便提一下,实际上forName方法里也是调用的ClassLoader的loadClass()方法来加载类信息的。
这里还有一步很关键的,就是加载类信息的时候发生了什么。我们看看 com.mysql.jdbc.Driver 的源码
public class Driver extends NonRegisteringDriver implements java.sql.Driver { // ~ Static fields/initializers // --------------------------------------------- // // Register ourselves with the DriverManager // static { try { java.sql.DriverManager.registerDriver(new Driver()); } catch (SQLException E) { throw new RuntimeException("Can't register driver!"); } } // ~ Constructors // ----------------------------------------------------------- /** * Construct a new driver and register it with DriverManager * * @throws SQLException * if a database error occurs. */ public Driver() throws SQLException { // Required for Class.forName().newInstance() } }
注意到这个static语句块了吧。就是这段代码,把自己注册到了DriverManager的driverlist里。
终于结束了,当所有驱动程序的Driver实例注册完毕,DriverManager就开始遍历这些注册好的驱动,对传入的数据库链接DSN调用这些驱动的connect方法,最后返回一个对应的数据库驱动类里的connect方法返回的java.sql.Connection实例,也就是我最开始那段测试代码里的conn。大家可以返回去看看DriverManager在initialize()结束后干了什么就明白
最后总结一下流程:
1. 调用 getConnection 方法
2. DriverManager 通过 SystemProerty jdbc.driver 获取数据库驱动类名
或者
通过ClassLoader.getSystemResources 去CLASSPATH里的类信息里查找 META-INF/services/java.sql.Driver 这个文件里查找获取数据库驱动名
3. 通过找的的driver名对他们进行类加载
4. Driver类在被加载的时候执行static语句块,将自己注册到DriverManager里去
5. 注册完毕后 DriverManager 调用这些驱动的connect方法,将合适的Connection 返回给客户端
相关文章推荐
- JDBC中驱动加载的过程分析
- JDBC中驱动加载的过程分析(上)
- JDBC中驱动加载的过程分析
- JDBC中驱动加载的过程分析(下)
- JDBC中驱动加载的过程分析
- jdbc驱动的类加载过程
- jdbc驱动的类加载过程
- JDBC中驱动加载的过程分析
- JDBC驱动加载全过程
- [OpenSolaris][kernel]Solaris内核加载设备驱动过程
- 加载JDBC驱动知多少!
- maven加载本地oracle的JDBC驱动
- USB HID设备驱动加载过程
- jdbc加载驱动
- 开机启动加载驱动过程中调用PostMessage函数出错
- Linux下加载JDBC驱动连接OceanBase
- jsp中使用jdbc驱动与sql2005连接和使用带参数的存储过程
- JDBC驱动加载程序
- IJ连接sql加载jdbc驱动
- 【数据库学习笔记】(2)JDBC加载并注册数据库驱动并连接数据库