【发布时间】:2021-08-24 13:35:23
【问题描述】:
我正在尝试将 ServiceLoader 与模块系统一起使用,与此处文档中 将服务提供者部署为模块 标题中所示的方式相同 - click
我有以下项目:
模块 tester.client
package tester.client;
import tester.common.Showable;
import java.util.ServiceLoader;
public class Main {
public static void main(String[] args) {
ServiceLoader<Showable> loader = ServiceLoader.load(Showable.class);
loader.findFirst().orElseThrow(); //throws Exception
}
}
模块信息.java
import tester.common.Showable;
module tester.client {
requires tester.common;
uses Showable;
}
模块 tester.common
package tester.common;
public interface Showable {
void show();
}
模块信息.java
module tester.common {
exports tester.common;
}
模块 tester.gui
package tester.gui;
import tester.common.Showable;
public class Window implements Showable {
@Override
public void show() {
}
}
模块信息.java
module tester.gui {
requires tester.common;
provides tester.common.Showable with tester.gui.Window;
}
问题:
ServiceLoader 不加载我的实现。
- tester.client 使用 Showable
- tester.common 导出 Showable
- tester.gui 提供带窗口的 Showable
【问题讨论】:
-
我无法重现问题,我猜你错过了 tester.client 中的 tester.gui 依赖项。
-
@samabcde 不,那将是一个设计缺陷:强烈建议该模块不要导出包含服务提供者的包。
-
我遵循了您在帖子中的内容,没有更改任何代码行。澄清一下,我的意思是 maven 依赖。
-
您需要“C:\Users\wikto\IdeaProjects\ModulesTest\out\production\tester.gui;”的模块路径(-p)
-
-p选项指定解析模块的位置,但这并不意味着将加载所有模块。您用-m指定了tester.client,它的唯一依赖项是tester.common。为确保加载其他模块,即tester.gui,您需要指定--add-modules。
标签: java java-module serviceloader