Issue
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.
Solution
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);
// [..]
}
Answered By - Thomas Kläger
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.