JDBC 驅動加載過程


參見如下簡單的程序

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()方法

 1     /**
 2      * Attempts to establish a connection to the given database URL.
 3      * The <code>DriverManager</code> attempts to select an appropriate driver from
 4      * the set of registered JDBC drivers.
 5      *
 6      * @param url a database url of the form 
 7      * <code>jdbc:<em>subprotocol</em>:<em>subname</em></code>
 8      * @param user the database user on whose behalf the connection is being
 9      *   made
10      * @param password the user's password
11      * @return a connection to the URL 
12      * @exception SQLException if a database access error occurs
13      */
14     public static Connection getConnection(String url, 
15     String user, String password) throws SQLException {
16         java.util.Properties info = new java.util.Properties();
17 
18         // Gets the classloader of the code that called this method, may 
19     // be null.
20     ClassLoader callerCL = DriverManager.getCallerClassLoader();
21 
22     if (user != null) {
23         info.put("user", user);
24     }
25     if (password != null) {
26         info.put("password", password);
27     }
28 
29         return (getConnection(url, info, callerCL));
30     }

 

 

2. 調用實際起作用的getConnection()方法

 1 //  Worker method called by the public getConnection() methods.
 2     private static Connection getConnection(
 3     String url, java.util.Properties info, ClassLoader callerCL) throws SQLException {
 4     java.util.Vector drivers = null;
 5         /*
 6      * When callerCl is null, we should check the application's
 7      * (which is invoking this class indirectly)
 8      * classloader, so that the JDBC driver class outside rt.jar
 9      * can be loaded from here.
10      */
11     synchronized(DriverManager.class) {  
12       // synchronize loading of the correct classloader.
13       if(callerCL == null) {
14           callerCL = Thread.currentThread().getContextClassLoader();
15        }    
16     } 
17      
18     if(url == null) {
19         throw new SQLException("The url cannot be null", "08001");
20     }
21     
22     println("DriverManager.getConnection(\"" + url + "\")");
23     
24     if (!initialized) {
25         initialize();
26     }
27 
28     synchronized (DriverManager.class){ 
29             // use the readcopy of drivers
30         drivers = readDrivers;  
31         }
32 
33     // Walk through the loaded drivers attempting to make a connection.
34     // Remember the first exception that gets raised so we can reraise it.
35     SQLException reason = null;
36     for (int i = 0; i < drivers.size(); i++) {
37         DriverInfo di = (DriverInfo)drivers.elementAt(i);
38       
39         // If the caller does not have permission to load the driver then 
40         // skip it.
41         if ( getCallerClass(callerCL, di.driverClassName ) != di.driverClass ) {
42         println("    skipping: " + di);
43         continue;
44         }
45         try {
46         println("    trying " + di);
47         Connection result = di.driver.connect(url, info);
48         if (result != null) {
49             // Success!
50             println("getConnection returning " + di);
51             return (result);
52         }
53         } catch (SQLException ex) {
54         if (reason == null) {
55             reason = ex;
56         }
57         }
58     }
59     
60     // if we got here nobody could connect.
61     if (reason != null)    {
62         println("getConnection failed: " + reason);
63         throw reason;
64     }
65     
66     println("getConnection: no suitable driver found for "+ url);
67     throw new SQLException("No suitable driver found for "+ url, "08001");
68     }

 這里有幾個比較重要的地方,一個L25的initialize()方法,下面是他的源碼

 1 // Class initialization.
 2     static void initialize() {
 3         if (initialized) {
 4             return;
 5         }
 6         initialized = true;
 7         loadInitialDrivers();
 8         println("JDBC DriverManager initialized");
 9     }
10 
11 private static void loadInitialDrivers() {
12         String drivers;
13     
14         try {
15         drivers = (String) java.security.AccessController.doPrivileged(
16         new sun.security.action.GetPropertyAction("jdbc.drivers"));
17         } catch (Exception ex) {
18             drivers = null;
19         }
20         
21         // If the driver is packaged as a Service Provider,
22         // load it.
23         
24         // Get all the drivers through the classloader 
25         // exposed as a java.sql.Driver.class service.
26     
27      DriverService ds = new DriverService();
28 
29      // Have all the privileges to get all the 
30      // implementation of java.sql.Driver
31      java.security.AccessController.doPrivileged(ds);       
32             
33         println("DriverManager.initialize: jdbc.drivers = " + drivers);
34         if (drivers == null) {
35             return;
36         }
37         while (drivers.length() != 0) {
38             int x = drivers.indexOf(':');
39             String driver;
40             if (x < 0) {
41                 driver = drivers;
42                 drivers = "";
43             } else {
44                 driver = drivers.substring(0, x);
45                 drivers = drivers.substring(x+1);
46             }
47             if (driver.length() == 0) {
48                 continue;
49             }
50             try {
51                 println("DriverManager.Initialize: loading " + driver);
52                 Class.forName(driver, true,
53                   ClassLoader.getSystemClassLoader());
54             } catch (Exception ex) {
55                 println("DriverManager.Initialize: load failed: " + ex);
56             }
57         }
58     }

這一段就是加載數據庫驅動的地方,以我用的connector/j為例,看L27,這個DriverService是一個內部類,代碼如下:

 1 // DriverService is a package-private support class.    
 2 class DriverService implements java.security.PrivilegedAction {
 3         Iterator ps = null;
 4     public DriverService() {};
 5         public Object run() {
 6 
 7     // uncomment the followin line before mustang integration   
 8         // Service s = Service.lookup(java.sql.Driver.class);
 9     // ps = s.iterator();
10 
11     ps = Service.providers(java.sql.Driver.class);
12 
13     /* Load these drivers, so that they can be instantiated. 
14      * It may be the case that the driver class may not be there
15          * i.e. there may be a packaged driver with the service class
16          * as implementation of java.sql.Driver but the actual class
17          * may be missing. In that case a sun.misc.ServiceConfigurationError
18          * will be thrown at runtime by the VM trying to locate 
19      * and load the service.
20          * 
21      * Adding a try catch block to catch those runtime errors
22          * if driver not available in classpath but it's 
23      * packaged as service and that service is there in classpath.
24      */
25         
26     try {
27            while (ps.hasNext()) {
28                ps.next();
29            } // end while
30     } catch(Throwable t) {
31         // Do nothing
32     }
33         return null;
34     } //end run
35 
36 } //end DriverService

L11的 sun.misc.Service.providers()方法是關鍵所在,代碼如下

  1     /**
  2      * Locates and incrementally instantiates the available providers of a
  3      * given service using the given class loader.
  4      *
  5      * <p> This method transforms the name of the given service class into a
  6      * provider-configuration filename as described above and then uses the
  7      * <tt>getResources</tt> method of the given class loader to find all
  8      * available files with that name.  These files are then read and parsed to
  9      * produce a list of provider-class names.  The iterator that is returned
 10      * uses the given class loader to lookup and then instantiate each element
 11      * of the list.
 12      *
 13      * <p> Because it is possible for extensions to be installed into a running
 14      * Java virtual machine, this method may return different results each time
 15      * it is invoked. <p>
 16      *
 17      * @param  service
 18      *         The service's abstract service class
 19      *
 20      * @param  loader
 21      *         The class loader to be used to load provider-configuration files
 22      *         and instantiate provider classes, or <tt>null</tt> if the system
 23      *         class loader (or, failing that the bootstrap class loader) is to
 24      *         be used
 25      * 
 26      * @return An <tt>Iterator</tt> that yields provider objects for the given
 27      *         service, in some arbitrary order.  The iterator will throw a
 28      *         <tt>ServiceConfigurationError</tt> if a provider-configuration
 29      *         file violates the specified format or if a provider class cannot
 30      *         be found and instantiated.
 31      *
 32      * @throws ServiceConfigurationError
 33      *         If a provider-configuration file violates the specified format
 34      *         or names a provider class that cannot be found and instantiated
 35      *
 36      * @see #providers(java.lang.Class)
 37      * @see #installedProviders(java.lang.Class)
 38      */
 39     public static Iterator providers(Class service, ClassLoader loader)
 40     throws ServiceConfigurationError
 41     {
 42     return new LazyIterator(service, loader);
 43     }
 44 
 45 /**
 46      * Private inner class implementing fully-lazy provider lookup
 47      */
 48     private static class LazyIterator implements Iterator {
 49 
 50     Class service;
 51     ClassLoader loader;
 52     Enumeration configs = null;
 53     Iterator pending = null;
 54     Set returned = new TreeSet();
 55     String nextName = null;
 56 
 57     private LazyIterator(Class service, ClassLoader loader) {
 58         this.service = service;
 59         this.loader = loader;
 60     }
 61 
 62     public boolean hasNext() throws ServiceConfigurationError {
 63         if (nextName != null) {
 64         return true;
 65         }
 66         if (configs == null) {
 67         try {
 68             String fullName = prefix + service.getName();
 69             if (loader == null)
 70             configs = ClassLoader.getSystemResources(fullName);
 71             else
 72             configs = loader.getResources(fullName);
 73         } catch (IOException x) {
 74             fail(service, ": " + x);
 75         }
 76         }
 77         while ((pending == null) || !pending.hasNext()) {
 78         if (!configs.hasMoreElements()) {
 79             return false;
 80         }
 81         pending = parse(service, (URL)configs.nextElement(), returned);
 82         }
 83         nextName = (String)pending.next();
 84         return true;
 85     }
 86 
 87     public Object next() throws ServiceConfigurationError {
 88         if (!hasNext()) {
 89         throw new NoSuchElementException();
 90         }
 91         String cn = nextName;
 92         nextName = null;
 93         try {
 94         return Class.forName(cn, true, loader).newInstance();
 95         } catch (ClassNotFoundException x) {
 96         fail(service,
 97              "Provider " + cn + " not found");
 98         } catch (Exception x) {
 99         fail(service,
100              "Provider " + cn + " could not be instantiated: " + x,
101              x);
102         }
103         return null;    /* This cannot happen */
104     }
105 
106     public void remove() {
107         throw new UnsupportedOperationException();
108     }
109 
110     }

好了。經過各種進入,終於到達了目的地,上面這段代碼就是加載數據庫驅動的所在,請看LazyIterator里的從L57開始的這一段

實際上很簡單,他就是去CLASSPATH里的library里找  META-INF/services/java.sql.Driver 這個文件,其中 java.sql.Driver 這個名字是通過上面的 service.getName()獲得的。 數據庫驅動的類里都會有 META-INF 這個文件夾,我們可以MySQL的connector/j數據庫驅動加到環境變量里后自己嘗試一下輸出,代碼如下

 1 package test;
 2 
 3 import java.io.IOException;
 4 import java.net.URL;
 5 import java.sql.Driver;
 6 import java.util.Enumeration;
 7 
 8 public class Test {
 9     public static void main(String[] args) throws IOException {
10         Enumeration<URL> list = ClassLoader.getSystemResources("META-INF/services/" + Driver.class.getName());
11         while (list.hasMoreElements()) {
12             System.out.println(list.nextElement());
13         }
14     }
15 }

控制台會輸出

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 的源碼

 1 public class Driver extends NonRegisteringDriver implements java.sql.Driver {
 2     // ~ Static fields/initializers
 3     // ---------------------------------------------
 4 
 5     //
 6     // Register ourselves with the DriverManager
 7     //
 8     static {
 9         try {
10             java.sql.DriverManager.registerDriver(new Driver());
11         } catch (SQLException E) {
12             throw new RuntimeException("Can't register driver!");
13         }
14     }
15 
16     // ~ Constructors
17     // -----------------------------------------------------------
18 
19     /**
20      * Construct a new driver and register it with DriverManager
21      * 
22      * @throws SQLException
23      *             if a database error occurs.
24      */
25     public Driver() throws SQLException {
26         // Required for Class.forName().newInstance()
27     }
28 }

注意到這個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 返回給客戶端


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM