Skip to content

Java ServiceLoader

Java ServiceLoader is a simple service-provider loading facility (java.util.ServiceLoader) used for implementing service discovery mechanisms^[600-developer-java-black-technology-serviceloader.md]. It functions as a utility class provided by the JDK to locate and load service implementation classes at runtime^[600-developer-java-black-technology-serviceloader.md].

Mechanism

The facility relies on a specific convention for resource location. Implementations are located by searching configuration files in the META-INF/services/ directory^[600-developer-java-black-technology-serviceloader.md]. Within this directory, a file must be created using the fully qualified name of the service interface; the contents of this file should list the concrete implementation classes that implement that interface^[600-developer-java-black-technology-serviceloader.md].

Usage Example

A practical application of ServiceLoader is found in the java.sql.DriverManager class, specifically within the loadInitialDrivers method^[600-developer-java-black-technology-serviceloader.md]. The code uses ServiceLoader.load(Driver.class) to retrieve an iterator of all drivers packaged as Service Providers^[600-developer-java-black-technology-serviceloader.md]. This iterator is then traversed to instantiate and load the available driver classes found in the classpath^[600-developer-java-black-technology-serviceloader.md].

  • [[Service Locator Pattern]]
  • [[Dependency Injection]]
  • [[SPI (Service Provider Interface)]]
  • [[Java JDBC]]

Sources

  • 600-developer-java-black-technology-serviceloader.md