问题
In this java document: https://docs.oracle.com/javase/9/docs/api/java/util/ServiceLoader.html Deploying service providers as modules chapter,it says:
com.example.impl.ExtendedCodecsFactory is a public class that does not implement CodecFactory, but it declares a public static no-args method named "provider" with a return type of CodecFactory.
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.
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.
回答1:
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;
}
To compile:
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:
Deploying service providers as modules
[...]
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.
That covers putting plain JARs without module descriptor onto the module path.
来源:https://stackoverflow.com/questions/48090929/confused-about-java-9-serviceloaderload-method-and-the-way-how-to-provide-a-se