Course contentsShow
← Java
Lesson 2498 of 2,87047. Java Platform Module System (JPMS)Free lesson

The Service Provider Interface (SPI) Pattern

Understanding how SPI enables loose coupling by separating interface from implementation through dynamic loading.

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:

  1. Define a service interface in one module (e.g., com.example.api defines MyService)
  2. Provide implementations in separate modules (e.g., com.example.impl1 provides MyServiceImplA)
  3. Use ServiceLoader to 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:

  • uses directive: Declares that your module consumes a service
  • provides...with directive: 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.