JDBCドライバロードプロセス

2965 ワード

mysql jdbcにロードされたdemoを例に挙げます.

  String url ="jdbc:mysql://localhost:3306/jdbcana";     
  String username = "root";
  String password = "root";
  Connection con = DriverManager.getConnection(url, username, password);

まず、

Connection con = DriverManager.getConnection(url, username, password)
このコードはconnectionを得て、コードにフォローします.

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));
}

まず、現在のクラスをロードするclassloaderを取得し、次にpropertiesファイルに属性を挿入します.
次にgetConnection(url,info,callerCL)メソッドを呼び出し、initialize()->loadInitialDrivers()を呼び出します.メソッド,loadInitialDrivers()メソッドではまずSystem.getpropertyで設定を取得するjdbc.driversプロパティは、設定されていない場合は無視され、次に呼び出されます.
DriverService ds = new DriverService();

 // Have all the privileges to get all the 
	 // implementation of java.sql.Driver
	 java.security.AccessController.doPrivileged(ds);

このメソッドはServicesを呼び出します.providers(Driver.class);方法、彼は実はString str=“META-INF/services/”+thisからです.service.getName();でクラスをロードします.このクラスがsunです.jdbc.odbc.JdbcOdbcDriver,
return Class.forName(str, true, this.loader).newInstance();生産例を見てsun.jdbc.odbc.JdbcOdbcDriverソースであり、JdbcOdbcDriver localJdbcOdbcDriver=new JdbcOdbcDriver()でもある.そしてDriverManager.registerDriver(localJdbcOdbcDriver);ドライバマネージャにドライバを登録し、Mysqljdbcと同じようにドライバコードを登録すると、ドライバ情報のパッケージ化されたDriverInfoがインスタンス化され、driver vetorにDriverInfoオブジェクトが追加され、初期化が完了した後、vetorからDriverInfoが取り出し、その後driverが取り出し、connectメソッドが呼び出され、urlが解析され、現在のドライバのルールに合致する場合は、jdbcが送信された場合など、現在のドライバを使用します.mysql://localhost:3306/jdbcanamysql jdbcで駆動していると解析できます.Mysql jdbcドライバはいつロードされますか.mysql jarパッケージをclasspath環境に追加するため、systemclassloaderは環境下のjarパッケージをロードします.Driverクラスにはstatic文ブロックがあります.

try {
			java.sql.DriverManager.registerDriver(new Driver());
		} catch (SQLException E) {
			throw new RuntimeException("Can't register driver!");
		}
	}
static {
あ、ここでもDriverManagerにdriverを登録しています.
総じて、すべてのデータベース・ベンダーが提供するドライバは、どのドライブが呼び出されるかを後でURLに基づいて判定するために、DriverMangerにregisterDriverする必要があります.一方、initialize->loadInitialDriversメソッドは、システムが提供するドライブをロードするか、jdbcがロード設定されているだけです.このシステムはpropertyのドライバ、その他のドライバの登録はclassloaderのロードメカニズムに依存し、static文ブロックによってクラスのロードを実現する