Implementing a Service Provider Module
What You'll Learn
You'll learn how to create a complete service provider module that supplies a concrete implementation of a service interface using the provides...with directive.
The Provider Module Architecture
Now that you've defined a service interface module (with uses) and understood the provides...with syntax, it's time to build an actual provider module. This module contains the concrete implementation class and declares it as a service provider.
A service provider module has three key responsibilities:
- Require the service interface module
- Implement the service interface with a concrete class
- Provide that implementation using
provides...with
Structure of a Provider Module
Your module-info.java looks like this:
module my.service.provider {
requires my.service.api; // Access the service interface
provides com.example.api.MyService
with com.example.provider.MyServiceImpl;
}
The implementation class lives in your module:
package com.example.provider;
import com.example.api.MyService;
public class MyServiceImpl implements MyService {
// Concrete implementation of interface methods
public void doWork() {
System.out.println("Provider implementation running");
}
}
Key Requirements
The implementation class must:
- Have a public no-argument constructor (or the default one)
- Implement the service interface fully
- Be accessible to
ServiceLoader(the package doesn't need to be exported!)
Think of it like a restaurant supplier: the consumer module orders "fresh produce" (the service interface), your provider module delivers specific "organic tomatoes" (the concrete implementation), and JPMS handles the logistics.
Key Takeaway:
A service provider module requires the service interface module, contains a concrete implementation class with a no-arg constructor, and declares that implementation using provides...with in its module descriptor—without needing to export the implementation package.