Why is my Java9 module service not working?
Asked Answered
S

1

6
---------------------------------------------
package org.zpf.service;
public interface Services {
    void test();
}
module org.zpf.service.Services {
    exports org.zpf.service;
}
---------------------------------------------
package org.zpf.impl;
import org.zpf.service.Services;

public class Impl implements Services {
@Override
public void test() {
    System.out.println("Impl-1");
 }
}

module org.zpf.impl.Impl {
    requires org.zpf.service.Services;
    provides org.zpf.service.Services with org.zpf.impl.Impl;
}
----------------------------------------------
public class Demo {
   public static void main(String[] args) {
      ServiceLoader.load(Services.class).forEach(Services::test);
   }
}

module org.zpf.demo.Demo {
    requires org.zpf.service.Services;
    uses org.zpf.service.Services;
}

I am running this code with IntelliJ IDEA, but it looks like the submodule is not running.The following is the output of the program:

/Library/Java/JavaVirtualMachines/jdk-11.0.1.jdk/Contents/Home/bin/java "-javaagent:/Applications/IntelliJ IDEA 2018.3.app/Contents/lib/idea_rt.jar=61434:/Applications/IntelliJ IDEA 2018.3.app/Contents/bin" -Dfile.encoding=UTF-8 -p /Users/tubetrue01/IDEA/Test/Demo/target/classes:/Users/tubetrue01/IDEA/Test/Services/target/classes -m org.zpf.demo.Demo/org.zpf.demo.Demo

Process finished with exit code 0
Satinwood answered 7/12, 2018 at 15:2 Comment(0)
P
2

All you need to do is to ensure that the module

module org.zpf.impl  // fixing the name from that of question

is present on the modulepath. Executing the command as shared by you from the command-line with an addition to the path of impl module works just as expected.

.../jdk-11.jdk/Contents/Home/bin/java -p .../Desktop/modular/out/production/demo:.../Desktop/modular/out/production/modular:.../Desktop/modular/out/production/impl -m org.zpf.demo.Demo/org.zpf.demo.Demo

prints the expted output

Impl-1

In your command-line (formatted just for readability)

-p /Users/tubetrue01/IDEA/Test/Demo/target/classes:
   /Users/tubetrue01/IDEA/Test/Services/target/classes

should be modified to something like

-p /Users/tubetrue01/IDEA/Test/Demo/target/classes:
   /Users/tubetrue01/IDEA/Test/Services/target/classes:
   /Users/tubetrue01/IDEA/Test/Impl/target/classes

With IntelliJ IDEA, you can do the same with the following steps :

  1. Project Structure > Modules
  2. Select the Demo module > Navigate to Dependencies
  3. Add dependency [Bottom Left of Modal (+)] > Module dependency
  4. Select Impl module and Apply.
  5. Run your Demo class now.
Pagandom answered 7/12, 2018 at 15:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.