我正在尝试使用 ServiceLoader 运行示例应用程序。为此,我创建了两个 JAR:
JAR 1) number-service.jar
META-INF/
META-INF/MANIFEST.MF
ok/
ok/service/
ok/service/NumberService.class
ok/main/
ok/main/App.class
META-INF/services/
META-INF/services/ok.service.NumberService
META-INF/services/ok.service.NumberService
有单行:ok.service.impl.NumberServiceImpl
META-INF/MANIFEST.mf
有Main-Class: ok.main.App
条目
并ok.main.App
加载提供者ok.service.NumberService
JAR 2) number-service-impl.jar
META-INF/
META-INF/MANIFEST.MF
ok/
ok/service/
ok/service/impl/
ok/service/impl/NumberServiceImpl.class
包含实现ok.service.NumberService
当命令运行为:
java -cp lib/number-service-impl.jar -jar lib/number-service.jar
java -cp ".:lib/number-service-impl.jar" -jar lib/number-service.jar
或(同一目录中的两个 JAR)
java -jar number-service.jar
未找到提供程序。
Exception in thread "main" java.util.ServiceConfigurationError: ok.service.NumberService: Provider ok.service.impl.NumberServiceImpl not found
at java.base/java.util.ServiceLoader.fail(ServiceLoader.java:588)
at java.base/java.util.ServiceLoader.access$200(ServiceLoader.java:390)
at java.base/java.util.ServiceLoader$LazyClassPathLookupIterator.nextProviderClass(ServiceLoader.java:1206)
at java.base/java.util.ServiceLoader$LazyClassPathLookupIterator.hasNextService(ServiceLoader.java:1215)
at java.base/java.util.ServiceLoader$LazyClassPathLookupIterator.hasNext(ServiceLoader.java:1259)
at java.base/java.util.ServiceLoader$2.hasNext(ServiceLoader.java:1294)
at java.base/java.util.ServiceLoader$ProviderSpliterator.tryAdvance(ServiceLoader.java:1478)
at java.base/java.util.Spliterator.forEachRemaining(Spliterator.java:326)
at java.base/java.util.stream.ReferencePipeline$Head.forEach(ReferencePipeline.java:591)
at ok.main.App.main(App.java:9)
无法弄清楚提供程序类是如何找不到的。请帮忙!
提前致谢。