JDBC DriverManager service loading¶
JDBC DriverManager service loading refers to the internal mechanism used by the Java DriverManager class to discover and load database drivers automatically via the java.util.ServiceLoader facility, rather than relying solely on manual class loading.^[600-developer-java-black-technology-serviceloader.md]
Overview¶
In modern Java environments (JDBC 4.0 and later), application developers are no longer required to explicitly call Class.forName() to load JDBC drivers. Instead, the DriverManager utilizes a service-provider loading facility to scan for available drivers on the classpath.^[600-developer-java-black-technology-serviceloader.md]
Implementation in DriverManager¶
The initialization occurs within the static block of the DriverManager class, specifically through the loadInitialDrivers() method^[600-developer-java-black-technology-serviceloader.md]. This method performs two main checks for drivers:
- System Property: It first checks the
jdbc.driverssystem property^[600-developer-java-black-technology-serviceloader.md]. - ServiceLoader Mechanism: It then uses
ServiceLoader.load(Driver.class)to locate any drivers packaged as Service Providers^[600-developer-java-black-technology-serviceloader.md].
Service Loading Process¶
The DriverManager delegates the discovery of implementations to the ServiceLoader^[600-developer-java-black-technology-serviceloader.md]. The core steps in this process are:
- Discovery:
ServiceLoadersearches for configuration files located in the directoryMETA-INF/services/^[600-developer-java-black-technology-serviceloader.md]. - Configuration: The name of the configuration file must match the fully qualified name of the service interface (e.g.,
java.sql.Driver). The content of the file lists the fully qualified names of the concrete implementation classes^[600-developer-java-black-technology-serviceloader.md]. - Iteration and Instantiation: The
DriverManageriterates through theServiceLoaderresults. By callingnext()on the iterator, it triggers the loading and instantiation of the driver classes found in the configuration files^[600-developer-java-black-technology-serviceloader.md]. This effectively replaces the oldersun.misc.Providersmechanism^[600-developer-java-black-technology-serviceloader.md].
Error Handling¶
The loading process includes error handling for cases where a driver is packaged as a service but the actual implementation class is missing from the runtime classpath. In such scenarios, a java.util.ServiceConfigurationError may be thrown during the iteration phase^[600-developer-java-black-technology-serviceloader.md].
Related Concepts¶
- Java ServiceLoader
- [[JDBC]]
Sources¶
- 600-developer-java-black-technology-serviceloader.md