Service Provider Interface

  • 在classpath下创建META-INF/services/
  • 在services文件夹下创建接口名字的文件,并在文件中添加实现的类列表
    1
    2
    3
    4
    5
    ServiceLoader<DriverService> serviceLoader = ServiceLoader.load(DriverService.class);
    for (DriverService ds : serviceLoader) {
    System.out.println(ds.getClass().getName());
    ds.onStartUp();
    }

源码解读

PREFIX就是定义好的文件

1
2
3
4
5
public final class ServiceLoader<S>
implements Iterable<S>
{

private static final String PREFIX = "META-INF/services/";

configsEnumeration<URL>类型,可以迭代

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
private boolean hasNextService() {
if (nextName != null) {
return true;
}
if (configs == null) {
try {
String fullName = PREFIX + service.getName();
if (loader == null)
configs = ClassLoader.getSystemResources(fullName);
else
configs = loader.getResources(fullName);
} catch (IOException x) {
fail(service, "Error locating configuration files", x);
}
}
while ((pending == null) || !pending.hasNext()) {
if (!configs.hasMoreElements()) {
return false;
}
pending = parse(service, configs.nextElement());
}
nextName = pending.next();
return true;
}