How to call a service from a module at a new created level in Java 9?

I have three modules: module-a, module-b, module-c. Module-a and module-b are in the boot layer. The layer for module-c is creating myself.

Module-a has one interface com.mod-a.Serviceand in its information module I have:

module module-a {
    exports com.mod-a;
}

Module-c implements com.mod-a.Serviceand in my module-info I have:

module module-c {
    requires module-a;
    provides com.mod-a.Service with com.mod-c.ServiceImpl;
}

Module-b creates a new level with module-c and calls the module-c service. In its modular information, I:

module module-b {
    requires module-a;
    requires java.management;
    requires slf4j.api;
    uses com.mod-a.Service;
}

In module -b, I create a new layer with module-c as follows:

ModuleFinder finder = ModuleFinder.of(moduleCPath);
ModuleLayer parent = ModuleLayer.boot();
Configuration cf = parent.configuration().resolve(finder, ModuleFinder.of(), Set.of("module-c"));
ClassLoader scl = ClassLoader.getSystemClassLoader();
ModuleLayer layer = parent.defineModulesWithOneLoader(cf, scl);
//the following line prints "module-c"
layer.modules().stream().map(Module::getName).forEach(System.out::println);

However, after creating the layer, I cannot call the service of module-c in module-b. The following code:

Iterable<Service> it = ServiceLoader.load(Service.class);
System.out.println("LINE 1");
for (Service service : it) {
     System.out.println("Service was called");
     service.doIt();
}
System.out.println("LINE 2");

outputs:

LINE 1
LINE 2

What's my mistake?

+4
source share
2 answers

ServiceLoader.load(Class) TCCL , , . , ServiceLoader.load(layer, Service.class), , .

resolve . , resolveAndBind - . uses com.mod-a.Service -b , , provides com.mod-a.Service .

+2

,

ServiceLoader.load(Service.class) 

ServiceLoader.load(Service.class, Thread.currentThread().getContextClassLoader())

Service.

, , - , , :

module module-c {
    requires module-a;
    provides com.mod-a.Service with com.mod-c.ServiceImpl;
    opens com.mod-c to module-a;
}

, ServiceLoader , .

+2

Source: https://habr.com/ru/post/1685967/


All Articles