Sub topic 12
Decoupling with services: uses and provides
This chapter assumes you can write a module-info.java with requires and exports, and that you have compiled and run modules from the module path. It also assumes you know Java interfaces.
The problem services solve
With requires, a consumer names the module it depends on. To use a French greeting, the app would need requires com.example.greeter.french, and it would be tied to that implementation. Swapping it for a Spanish one means editing the descriptor and recompiling.
A service is an interface (or abstract class) whose implementations are found at run time. The consumer depends only on the interface. Provider modules say which implementations they offer, and the module system connects the two.
The three pieces
| Piece | Where it appears | Meaning |
|---|---|---|
| Service type | An exported package, usually in the API module | The interface consumers program against |
| `uses` | Consumer's `module-info.java` | This module will look up providers of the service type |
| `provides ... with` | Provider's `module-info.java` | This module supplies the named implementation classes |
A complete example
The API module defines the service interface and exports its package.
// src/com.example.greeter/module-info.java
module com.example.greeter {
exports com.example.greeter.api;
}
// src/com.example.greeter/com/example/greeter/api/GreetingProvider.java
package com.example.greeter.api;
public interface GreetingProvider {
String greet(String name);
}The provider module requires the API module and declares its implementation. It does not export the implementation package, so the class stays hidden.
// src/com.example.greeter.french/module-info.java
module com.example.greeter.french {
requires com.example.greeter;
provides com.example.greeter.api.GreetingProvider
with com.example.greeter.french.FrenchGreeting;
}
// src/com.example.greeter.french/com/example/greeter/french/FrenchGreeting.java
package com.example.greeter.french;
import com.example.greeter.api.GreetingProvider;
public class FrenchGreeting implements GreetingProvider {
@Override
public String greet(String name) {
return "Bonjour, " + name;
}
}The consumer declares uses and calls ServiceLoader. It does not require the French module.
// src/com.example.app/module-info.java
module com.example.app {
requires com.example.greeter;
uses com.example.greeter.api.GreetingProvider;
}
// src/com.example.app/com/example/app/Main.java
package com.example.app;
import com.example.greeter.api.GreetingProvider;
import java.util.ServiceLoader;
public class Main {
public static void main(String[] args) {
ServiceLoader<GreetingProvider> loader =
ServiceLoader.load(GreetingProvider.class);
for (GreetingProvider provider : loader) {
System.out.println(provider.greet("monde"));
}
}
}Compile all three modules and run the app:
javac -d out --module-source-path src \
-m com.example.app,com.example.greeter.french
java --module-path out -m com.example.app/com.example.app.MainYou must name the French module in -m when compiling, because nothing requires it, so the compiler would not otherwise build it. At run time, java performs service binding during resolution. It adds any observable module on the module path that provides a service used by a resolved module. The output is Bonjour, monde. Delete the French module from out and the program runs and prints nothing.
Looking up providers
ServiceLoader offers more than the iterator.
import com.example.greeter.api.GreetingProvider;
import java.util.ServiceLoader;
public class Lookup {
public static void main(String[] args) {
ServiceLoader<GreetingProvider> loader =
ServiceLoader.load(GreetingProvider.class);
// First provider, if any
loader.findFirst()
.ifPresent(p -> System.out.println(p.greet("world")));
// Inspect providers without instantiating them
loader.stream()
.map(ServiceLoader.Provider::type)
.forEach(t -> System.out.println(t.getName()));
// Instantiate every provider
loader.stream()
.map(ServiceLoader.Provider::get)
.forEach(p -> System.out.println(p.greet("all")));
}
}Class Lookup must live in a module that declares uses for GreetingProvider.
Iteration is lazy. The loader instantiates each provider when you reach it, and it caches the instances. Use stream() when you want to filter on the provider class before paying for construction. Call reload() to clear the cache.
Rules for providers
A provider implementation must be one of the following:
- A public class with a public no-argument constructor. It must be a top-level class or a public static nested class.
- Any type with a
public staticmethod namedprovider()that takes no arguments and returns the service type (or a subtype). Here the implementation class itself does not need a public constructor.
The second form lets you return a shared instance or choose an implementation at run time:
package com.example.greeter.french;
import com.example.greeter.api.GreetingProvider;
public class FrenchGreetingFactory {
private FrenchGreetingFactory() {}
public static GreetingProvider provider() {
return name -> "Salut, " + name;
}
}Its descriptor entry is provides com.example.greeter.api.GreetingProvider with com.example.greeter.french.FrenchGreetingFactory;.
Other rules:
- A
providesclause may list several implementations, separated by commas.ServiceLoaderreturns them in the listed order. - The implementation must be in the same module as the
providesdirective. - The provider's package does not need to be exported. Encapsulation still holds, and
ServiceLoaderreaches the class on the module system's behalf. - When several providers exist, the order across modules is not something to rely on. If you need a preference, add a method such as
int priority()to the service interface and sort.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `ServiceConfigurationError: ... module com.example.app does not declare uses` | The calling module has no `uses` for the service type | Add `uses` to the module that calls `ServiceLoader.load` |
| Loader is empty, no error | The provider module is not on the module path, or was not resolved | Put it on `--module-path`, or force it with `--add-modules com.example.greeter.french` |
| `ServiceConfigurationError: ... Provider ... not a subtype` | The implementation does not implement the service interface | Fix the `with` class |
| Compile error: package is not visible | The service interface package is not exported | Export the API package |
| Provider not found when the app is a plain `jar` on the classpath | Classpath providers use `META-INF/services` files, not `provides` | Add `META-INF/services/<service-type-name>` to the jar |
The last row matters for migration. The module system and the classpath each have their own registration mechanism. A modular jar placed on the classpath is treated as ordinary classpath code, so its provides directive is ignored. Conversely, an automatic module or a jar on the module path can still register providers through META-INF/services.
A uses directive also matters when you build a runtime image. jlink does not include provider modules by default, since nothing requires them. Pass --bind-services to include them, or list them in --add-modules:
jlink --module-path "$JAVA_HOME/jmods:out" \
--add-modules com.example.app,com.example.greeter.french \
--launcher app=com.example.app/com.example.app.Main \
--output imageExercise
A module shop.core defines PaymentMethod in its exported package shop.core.api. A second module shop.paypal has requires shop.core; and a public class PayPalMethod implements PaymentMethod. The checkout module shop.app calls ServiceLoader.load(PaymentMethod.class) and finds no providers, with no exception. Give the directives you would add, and in which modules, so the loader finds PayPalMethod. Also name one thing to check about the module path.
Show answer
Add provides shop.core.api.PaymentMethod with shop.paypal.PayPalMethod; to shop.paypal's descriptor. Add uses shop.core.api.PaymentMethod; to shop.app's descriptor. (If the uses were missing, the loader would throw ServiceConfigurationError, so a silent empty result points mainly to the missing provides.) Also check that shop.paypal is on the module path at launch, because service binding only considers observable modules. You can confirm resolution with java --module-path ... --list-modules.