The 'provides...with' Directive in module-info.java
What you'll learn: How to declare that your module provides an implementation of a service interface for other modules to consume via ServiceLoader.
The Core Idea
In the previous lesson, you learned about the uses directive, which declares that a module consumes a service. Now we flip to the provider side: the provides...with directive declares that your module implements and supplies a service interface.
Think of it like a restaurant menu system: uses is a customer saying "I want to order Italian food," while provides...with is a specific restaurant saying "I serve Italian food, and here's my chef who'll make it."
Syntax and Structure
The provides...with directive follows this pattern:
provides <service-interface> with <implementation-class>;
For example, if you have a com.example.spi.PaymentProcessor interface and your module provides an implementation called com.example.impl.StripeProcessor, you'd write:
module payment.stripe.provider {
provides com.example.spi.PaymentProcessor
with com.example.impl.StripeProcessor;
}
How It Works
When another module declares uses com.example.spi.PaymentProcessor, the ServiceLoader can discover your implementation at runtime through the module system's metadata. Your implementation class must:
- Implement the service interface
- Have a public no-argument constructor (or a public static
provider()method returning the service type)
You can provide multiple implementations in one module by repeating the directive, or even provide multiple service types.
Why It Matters
The provides...with directive enables true plugin architectures and extensibility. Consumer modules don't need compile-time dependencies on provider modules—they discover implementations dynamically, making your system highly modular and flexible.
Key Takeaway: The provides...with directive declares that your module supplies an implementation of a service interface, enabling loose coupling and dynamic service discovery through the JPMS and ServiceLoader mechanism.