问题描述
在此Java文档中: https://docs.oracle.com/javase/9/docs/api/java/util/ServiceLoader.html 将服务提供商部署为模块一章,内容为:
In this java document:https://docs.oracle.com/javase/9/docs/api/java/util/ServiceLoader.htmlDeploying service providers as modules chapter,it says:
但是事实是我不能使用provides...with
提供服务实现,如果不实现该服务,它将抛出编译错误和运行时错误.
But the fact is I can't use provides...with
to provide a service implementation and it will throw a compile error and runtime error without implement the service.
是否可以提供公共静态提供程序方法,并且可以在模块信息文件中不定义provides...with
的情况下提供服务实现?感到困惑,希望有人可以帮助您.
Is that possible I provide a public static provider method and I can provide a service implementation without define provides...with
in module-info file?Confused,hope someone can help.
推荐答案
只要带有provider方法的类最终出现在模块中,就可以正常工作.我刚刚创建了一个小型演示项目,它显示:
As long as the class with the provider method ends up in a module, this works fine. I just created a small demo project showing that:
// MODULE com.example.codec.api
public interface CodecFactory { }
module com.example.codec.api {
exports com.example.codec;
uses com.example.codec.CodecFactory;
}
// MODULE com.example.codec.api
public class ExtendedCodecsFactory {
public static CodecFactory provider() {
return new CodecFactory() { };
}
}
module com.example.codec.impl {
requires com.example.codec.api;
provides com.example.codec.CodecFactory
with com.example.impl.ExtendedCodecsFactory;
}
要编译:
javac
-d classes/com.example.codec.api
src/com.example.codec.api/module-info.java
src/com.example.codec.api/com/example/codec/CodecFactory.java
javac
-p classes/com.example.codec.api
-d classes/com.example.codec.impl
src/com.example.codec.impl/module-info.java
src/com.example.codec.impl/com/example/impl/ExtendedCodecsFactory.java
如果您尝试创建不在模块中的服务提供者,则提供者方法将不起作用.不幸的是,文档并不十分清楚在这方面. 在类路径上部署服务提供程序这一节既没有提到提供程序构造函数,也没有提到提供程序方法,实际上甚至没有提到继承.
If you're trying to create a service provider that does not live in a module, the provider methods won't work. Unfortunately, the documentation is not terribly clear in this regard. The section Deploying service providers on the class path mentions neither provider constructors nor provider methods, in fact it doesn't even mention inheritance.
您获得的最接近的信息是在上面的部分中:
The closest you get is in the section above that:
在应用程序模块路径上作为自动模块部署的服务提供程序必须具有提供程序构造函数.在这种情况下,不支持提供者方法.
A service provider that is deployed as an automatic module on the application module path must have a provider constructor. There is no support for a provider method in this case.
这涉及将没有模块描述符的普通JAR放入模块路径.
That covers putting plain JARs without module descriptor onto the module path.
这篇关于对Java 9 ServiceLoader :: load方法和如何提供服务的方式感到困惑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!