Skip to content

JDBC driver loading via ServiceLoader

JDBC driver loading via ServiceLoader is the standard mechanism by which the Java runtime automatically discovers and loads database driver implementations without requiring explicit manual registration in application code^[600-developer__java__black-technology__ServiceLoader.md].

Mechanism

The java.sql.DriverManager class utilizes a static initialization block to trigger the loading process^[600-developer__java__black-technology__ServiceLoader.md]. This block calls the loadInitialDrivers() method, which performs two checks: first, it attempts to read the jdbc.drivers system property, and second, it uses the ServiceLoader facility to find drivers packaged as Service Providers^[600-developer__java__black-technology__ServiceLoader.md].

The ServiceLoader locates implementations by looking for configuration files within the META-INF/services/ directory of the jar file^[600-developer__java__black-technology__ServiceLoader.md]. Specifically, it identifies a file named after the service interface (in this context, java.sql.Driver) which contains the fully qualified names of the concrete implementation classes^[600-developer__java__black-technology__ServiceLoader.md].

Execution Flow

During the loadInitialDrivers() routine, the DriverManager obtains an iterator for Driver.class services^[600-developer__java__black-technology__ServiceLoader.md]. It traverses this iterator, invoking next() on each element to trigger the instantiation of the driver class^[600-developer__java__black-technology__ServiceLoader.md]. This traversal effectively replaces the older sun.misc.Providers method and allows drivers to register themselves automatically via Class.forName logic internally handled by the iterator^[600-developer__java__black-technology__ServiceLoader.md].

Sources

^[600-developer__java__black-technology__ServiceLoader.md]