How do you use ServiceLoader and services with a simple code example?

The Java ServiceLoader is a utility that enables applications to discover and load service implementations at runtime. By defining a service interface and providing one or more implementations of it, ServiceLoader simplifies the process of loosely coupling components in an application. Below is a simple example demonstrating how to use ServiceLoader to load services in Java.

import java.util.ServiceLoader; // Define a service interface public interface GreetingService { void greet(String name); } // Implement the service interface public class EnglishGreetingService implements GreetingService { public void greet(String name) { System.out.println("Hello, " + name + "!"); } } // Main application to load the service public class ServiceLoaderExample { public static void main(String[] args) { ServiceLoader serviceLoader = ServiceLoader.load(GreetingService.class); for (GreetingService service : serviceLoader) { service.greet("John Doe"); } } }

Java ServiceLoader services service interface Java services runtime loading Java example loose coupling