Home > Enterprise >  How JAVA11 use SPI to load SQL Driver Class
How JAVA11 use SPI to load SQL Driver Class

Time:03-10

In Java8 there is a static block in java.sql.DriverManger class as

    static {
        loadInitialDrivers();
        println("JDBC DriverManager initialized");
    }

It will be executed when java.sql.DriverManger class is loaded by ClassLoader, and it will call the ServiceLoader.load() method to start to scan files under META-IFO/services folder in jars under the classpath. In this way it register all the Driver class defined in services folder.
However, in Java11, it don't have this static block anymore, I was wondering how Java11 starts the SPI process. Thanks for any answers.

CodePudding user response:

In Java 11 the scanning for the drivers is only started when the first connection is opened:

DriverManager.getConnection(String url)

public static Connection getConnection(String url)
    throws SQLException {

    java.util.Properties info = new java.util.Properties();
    return (getConnection(url, info, Reflection.getCallerClass()));
}

calls DriverManager.getConnection(String url, Properties info, Class<?> caller):

private static Connection getConnection(
    String url, java.util.Properties info, Class<?> caller) throws SQLException {
    // [..]
    ensureDriversInitialized();
    // [..]
}

which in turn calls DriverManager.ensureDriversInitialized() which finally uses the java.util.ServiceLoader class to effectively load the drivers:

private static void ensureDriversInitialized() {
    // [..]
                    ServiceLoader<Driver> loadedDrivers = ServiceLoader.load(Driver.class);
    // [..]
}
  • Related