Use ServiceLoader class to obtain service instance

In the "main-app" module, the `HelloInterface` service instance, `HelloModules`, was just being treated like an ordinary class that was exported from the "hello.modules" module. The code was not treating the class as a service class. This is not a good example of how services are used.

This commit makes use of the `ServiceLoader` class, which provides access to the `HelloInterface` instance as defined in the "hello.modules" module. This serves as a better example for how services are used.
This commit is contained in:
Michael Angstadt 2020-05-26 15:46:28 -04:00 committed by GitHub
parent 7b53c3cb55
commit 388f03ae9a
1 changed files with 6 additions and 3 deletions

View File

@ -1,12 +1,15 @@
package com.baeldung.modules.main;
import com.baeldung.modules.hello.HelloInterface;
import com.baeldung.modules.hello.HelloModules;
import java.util.ServiceLoader;
public class MainApp {
public static void main(String[] args) {
HelloModules.doSomething();
HelloModules module = new HelloModules();
module.sayHello();
Iterable<HelloInterface> services = ServiceLoader.load(HelloInterface.class);
HelloInterface service = services.iterator().next();
service.sayHello();
}
}