Loading Services with ServiceLoader.load()
What you'll learn: How to use ServiceLoader.load() to discover and iterate through all available service provider implementations at runtime.
The Core Idea
Once you've declared uses in your consumer module and provides...with in your provider module(s), you need to actually find and use those service implementations. The ServiceLoader.load() method performs this discovery for you, scanning the module path and returning an iterable collection of all registered providers.
Think of ServiceLoader as a registry desk at a convention center. You tell it what kind of service you're looking for (the interface type), and it hands you a list of everyone who's registered to provide that service. You can then walk through the list and use whichever providers you need.
Basic Usage Pattern
// In your consumer module
ServiceLoader<MyService> loader = ServiceLoader.load(MyService.class);
// Iterate through all discovered providers
for (MyService provider : loader) {
provider.performWork();
}
The load() method takes a Class object representing your service interface and returns a ServiceLoader instance. This loader is Iterable, so you can use it in a for-each loop to access each discovered implementation.
Key Points
- Lazy Loading: Providers are instantiated on-demand as you iterate, not all at once.
- Multiple Providers: If multiple modules provide the same service, you'll get all of them.
- No Manual Configuration: The module system handles discovery automatically—no classpath scanning or configuration files needed.
Key Takeaway:
ServiceLoader.load(ServiceInterface.class) discovers all modules that provides the specified service, returning an iterable collection you can loop through to access each implementation.