The Service Provider Interface (SPI) Pattern
What you'll learn: How the SPI pattern enables dynamic, loosely-coupled architectures by separating interface definitions from their runtime implementations.
What Is the SPI Pattern?
The Service Provider Interface (SPI) is a design pattern where an interface (or abstract class) is defined by one module, but implementations are discovered and loaded dynamically at runtime from other modules. This creates a "plug-in" architecture where the consumer doesn't need compile-time knowledge of concrete implementations.
Think of it like a restaurant menu (the interface) that lists "Dessert" — but the actual dessert served depends on which chef (implementation provider) is working that day. The customer orders from the menu without knowing which specific dessert they'll get until runtime.
How SPI Achieves Loose Coupling
In traditional tightly-coupled designs, you'd write:
MyServiceImpl service = new MyServiceImpl(); // Hard-coded dependency
With SPI, you instead:
- Define a service interface in one module (e.g.,
com.example.apidefinesMyService) - Provide implementations in separate modules (e.g.,
com.example.impl1providesMyServiceImplA) - Use
ServiceLoaderto discover and load implementations dynamically — no direct constructor calls
The consumer only depends on the interface, never the concrete class. Implementations can be swapped, added, or removed without recompiling the consumer.
Why This Matters in JPMS
JPMS enhances SPI through:
usesdirective: Declares that your module consumes a serviceprovides...withdirective: Registers implementations- Strong encapsulation: Implementation internals stay hidden; only the service interface is exposed
The module system handles discovery automatically, respecting module boundaries while maintaining encapsulation.
Key Takeaway:
The SPI pattern separates "what" (interface) from "who" (implementation) through dynamic loading, enabling plug-and-play architectures where providers and consumers remain loosely coupled and independently deployable.