JPMS ServiceLoader does not work for me as expected.
I am trying to provide a desktop program as an executable jar with a default service, that can be overloaded by the individual user. A user provides their own service class and give their name as an argument on the commandline.
The service:
package eu.ngong.myService;
public interface MyService {
public String name();
public void doSomething();
}
The program together with the default service (the first lines in the if and the for are inserted for logging):
package eu.ngong.myService;
import java.util.ServiceLoader;
public class ServiceUser implements MyService {
private static MyService myService = new ServiceUser();
public static void main(String[] args) {
if (args.length > 0) {
System.out.println("trying to load " + args[0] + " envirionment.");
ServiceLoader<MyService> myServices = ServiceLoader.load(MyService.class);
for (MyService ms : myServices) {
System.out.println(ms.name());
if (ms.name().equalsIgnoreCase(args[0])) {
myService = ms;
}
}
}
myService.doSomething();
}
@Override
public void doSomething() {
System.out.println("The default service is acting.");
}
@Override
public String name() {
return "Default";
}
}
Both collected in myService.jar with the main class of ServiceUser hosting the module-info.java
module MyService {
exports eu.ngong.myService;
provides eu.ngong.myService.MyService with eu.ngong.myService.ServiceUser;
}
An individual jar at a user may be
package eu.ngong.user1;
import eu.ngong.myService.MyService;
public class User1 implements MyService {
@Override
public String name() {
return "User1";
}
@Override
public void doSomething() {
System.out.println("User1 is acting.");
}
}
with the module-info.java
module User1 {
requires MyService;
provides eu.ngong.myService.MyService with eu.ngong.user1.User1;
}
However, running the program with
java -p ..\user1\user1.jar;myService.jar -jar myService.jar User1
leads only to the unexpected output
trying to load User1 environment.
The default service is acting.
While I expected with logging
trying to load User1 environment.
Default
User1
User1 is acting.
What did I miss?
eu.ngong.myService.ServiceUser
? And, did you add aMETA-INF/eu.ngong.myService.MyService
referencing the implementation? – Minster-jar
versus-m
should be mostly similar. TheMETA-INF/services
is a good suggestion, but as long as modules are recognized as explicit, that might not be required either in my opinion. – Reformer