Skip to content

Commit f752e6b

Browse files
authored
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.
1 parent 86121f2 commit f752e6b

1 file changed

Lines changed: 6 additions & 3 deletions

File tree

  • core-java-modules/core-java-9-jigsaw/src/simple-modules/main.app/com/baeldung/modules/main
Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,15 @@
11
package com.baeldung.modules.main;
22

3+
import com.baeldung.modules.hello.HelloInterface;
34
import com.baeldung.modules.hello.HelloModules;
5+
import java.util.ServiceLoader;
46

57
public class MainApp {
68
public static void main(String[] args) {
79
HelloModules.doSomething();
8-
9-
HelloModules module = new HelloModules();
10-
module.sayHello();
10+
11+
Iterable<HelloInterface> services = ServiceLoader.load(HelloInterface.class);
12+
HelloInterface service = services.iterator().next();
13+
service.sayHello();
1114
}
1215
}

0 commit comments

Comments
 (0)