问题描述
我的 ServiceLoader 不想加载我的新服务.我想我已经正确设置了所有内容.
My ServiceLoader dont want to load my new service. I think I have everything correctly setted up.
核心.主
public class Main {
public static void main(String[] args) {
System.out.println("Before");
Iterator<IService> services = ServiceLoader.load(IService.class).iterator();
while (services.hasNext()) {
IService service = services.next();
System.out.println(service.sayHi());
}
System.out.println("After");
}
}
Core.service.IService
Core.service.IService
package service;
public interface IService {
String sayHi();
}
DbDataBuilder.builder.DbDataBuilder
DbDataBuilder.builder.DbDataBuilder
package builder;
import service.IService;
public class DbDataBuilder implements IService {
public DbDataBuilder() {
}
public String sayHi() {
return "I am Data Builder";
}
}
META-INF/services/service.Iservice
META-INF/services/service.Iservice
builder.DbDataBuilder
但是当我运行它时,控制台输出是:
But when I run it, console output is:
Before
After
我有什么问题吗?
推荐答案
ServiceLoader 当构建器在运行时位于类路径上时很有用,而不是在编译时.您应该将具有编译范围依赖的第三个模块添加到 Core 并将运行时范围依赖添加到 DbDataBuilder,将 Main 移动到第三个模块并享受 ServiceLoader 功能
ServiceLoader is useful when builder is on classpath at runtime, not at compile time. You should add third module with compile scope dependency to Core and runtime scope dependency to DbDataBuilder, move Main to the third module and enjoy ServiceLoader features
这篇关于ServiceLoader 未加载新服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!