Skip to content

Java service discovery mechanism

The Java service discovery mechanism is a provider-loading facility that enables a runtime to find and load implementations of a specific service interface.^[600-developer-java-black-technology-serviceloader.md] The core of this mechanism is the java.util.ServiceLoader class, which is a standard tool provided by the JDK for searching for service providers.^[600-developer-java-black-technology-serviceloader.md]

Configuration

To be discoverable, service providers must adhere to a specific directory convention. A file named after the fully qualified name of the service interface must be placed in the META-INF/services/ directory within the JAR.^[600-developer-java-black-technology-serviceloader.md] This file contains the fully qualified names of the concrete classes that implement the service interface.^[600-developer-java-black-technology-serviceloader.md]

Application Examples

A prominent application of this mechanism is found in the JDBC DriverManager. During initialization, DriverManager uses ServiceLoader to locate driver implementations bundled as service providers, effectively replacing the older sun.misc.Providers mechanism.^[600-developer-java-black-technology-serviceloader.md]

The process involves calling ServiceLoader.load(Driver.class) to obtain an iterator of available drivers.^[600-developer-java-black-technology-serviceloader.md] As the iterator traverses the available providers, the underlying mechanism typically invokes operations equivalent to Class.forName to instantiate the driver classes listed in the configuration files.^[600-developer-java-black-technology-serviceloader.md]

  • [[JDBC]]
  • [[Java SPI]]
  • [[Interface-based programming]]

Sources

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