ServiceLoader¶
ServiceLoader is a simple service-provider loading facility available in Java (specifically java.util.ServiceLoader).^[600-developer__java__black-technology__ServiceLoader.md] It functions as a utility class provided by the JDK to locate and load service implementations dynamically at runtime.^[600-developer__java__black-technology__ServiceLoader.md]
Mechanism¶
The facility relies on a specific directory structure and file placement within the classpath. To register a service, a file must be created inside the META-INF/services/ directory.^[600-developer__java__black-technology__ServiceLoader.md] The name of this file must match the fully qualified name of the service interface. The content of the file should list the concrete implementation classes that implement that service interface.^[600-developer__java__black-technology__ServiceLoader.md]
When the application runs, ServiceLoader utilizes the context class loader to scan this directory, reads the configuration files, and loads the specified implementation classes.^[600-developer__java__black-technology__ServiceLoader.md]
Usage Example¶
A practical application of ServiceLoader is found in the java.sql.DriverManager class. During initialization, the DriverManager uses ServiceLoader.load() to discover all JDBC drivers that are packaged as Service Providers.^[600-developer__java__black-technology__ServiceLoader.md]
The following workflow demonstrates how it functions within the DriverManager:
- Discovery: The system retrieves an iterator of
Driverobjects viaServiceLoader.load(Driver.class).^[600-developer__java__black-technology__ServiceLoader.md] - Iteration: The code iterates through the available drivers using
driversIterator.hasNext().^[600-developer__java__black-technology__ServiceLoader.md] - Loading: As the iterator progresses, it triggers the loading and instantiation of the driver implementation classes found in the
META-INF/services/directory.^[600-developer__java__black-technology__ServiceLoader.md]
This mechanism replaces older approaches (like sun.misc.Providers) and allows for automatic driver registration without requiring manual Class.forName calls in user code for every driver.^[600-developer__java__black-technology__ServiceLoader.md]
Related Concepts¶
- Java
- [[JDBC]]
- [[Dependency Injection]]
- [[SPI]]
Sources¶
600-developer__java__black-technology__ServiceLoader.md