【问题标题】:Why is my Java9 module service not working?为什么我的 Java9 模块服务不起作用?
【发布时间】:2019-05-09 08:52:19
【问题描述】:
---------------------------------------------
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;
}

我正在用 IntelliJ IDEA 运行这段代码,但是看起来子模块没有运行。以下是程序的输出:

/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

【问题讨论】:

    标签: java service java-9 java-module module-path


    【解决方案1】:

    您需要做的就是确保模块

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

    存在于模块路径中。从命令行执行您共享的命令,并添加到impl 模块的路径,正如预期的那样。

    .../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
    

    打印扩展输出

    Impl-1
    

    在您的命令行中(格式化只是为了便于阅读)

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

    应该修改成类似

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

    使用 IntelliJ IDEA,您可以执行以下步骤:

    1. 项目结构 > 模块
    2. 选择Demo 模块> 导航到依赖项
    3. 添加依赖 [Modal 左下角 (+)] > 模块依赖
    4. 选择Impl 模块并应用。
    5. 现在运行Demo 课程。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-28
      相关资源
      最近更新 更多