2. SPI的应用-java.sql.DriverManager

一般通过DriverManager.getConnection(url, username, password)拿到db的连接对象
我们具体跟下代码:

  1. DriverManager有下面的静态块将会首先执行
static {
        loadInitialDrivers();
        println("JDBC DriverManager initialized");
    }

private static void loadInitialDrivers() {
       ......
    
      // 主要代码就下面这些
      ServiceLoader loadedDrivers = ServiceLoader.load(Driver.class);
      Iterator driversIterator = loadedDrivers.iterator();
      try{
             while(driversIterator.hasNext()) {
                 driversIterator.next();
             }
         } catch(Throwable t) {
                // Do nothing
          }
    //其他代码,不管
    .......
}

从上面可以看到通过SPI拿到了所有Driver对象的实例,其中会对每个Driver实现类初始化

  1. 看下com.mysql.jdbc.Driver
static {
        try {
                        // 注册到DriverManager中去, 
            java.sql.DriverManager.registerDriver(new Driver());
        } catch (SQLException E) {
            throw new RuntimeException("Can't register driver!");
        }
    }
  1. DriverManager.getConnection()
for(DriverInfo aDriver : registeredDrivers) {
    if(isDriverAllowed(aDriver.driver, callerCL)) {
        try {
            // 获取Connection
            Connection con = aDriver.driver.connect(url, info);
            if (con != null) {
                return (con);
            }
        } catch (SQLException ex) {
            if (reason == null) {
                reason = ex;
            }
        }

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

}

参考
https://juejin.im/post/5a6036d5518825734107f96d
https://blog.csdn.net/xieyuooo/article/details/8502585

你可能感兴趣的:(2. SPI的应用-java.sql.DriverManager)