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:
parent
7b53c3cb55
commit
388f03ae9a
|
@ -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();
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue