SPI,全程為Service Provider Interface,是一種服務(wù)發(fā)現(xiàn)機制.它通過在ClassPath下META-INF/services文件夾查找文件,自動加載文件中所定義的類.
在這個過程中,可以通過ServiceLoader.load以及ServiceLoader.iterator來獲取文件中定義的實現(xiàn)類
其中,文件名為接口的全限定名,文件中的定義的類是該接口的實現(xiàn)類的全限定名
ServiceLoader部分源碼如下:
ServiceLoader.load() 主要是初始化對象
public final class ServiceLoader<S>
implements Iterable<S>
{
//定義查詢文件的目錄
private static final String PREFIX = "META-INF/services/";
//要加載的接口
private final Class<S> service;
//類加載器
private final ClassLoader loader;
private final AccessControlContext acc;
//緩存已加載的實現(xiàn)類
private LinkedHashMap<String,S> providers = new LinkedHashMap<>();
//ServiceLoader 的內(nèi)部類,由它實現(xiàn)加載
private LazyIterator lookupIterator;
public static <S> ServiceLoader<S> load(Class<S> service,
ClassLoader loader)
{ //初始化ServiceLoader
return new ServiceLoader<>(service, loader);
}
//load 方法,主要做ServiceLoad 及其內(nèi)部類 LazyIterator 初始化(service,loader),
public static <S> ServiceLoader<S> load(Class<S> service) {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
return ServiceLoader.load(service, cl);
}
public void reload() {
providers.clear();
//初始化內(nèi)部類LazyIterator
lookupIterator = new LazyIterator(service, loader);
}
//校驗service是否為空,初始化ServiceLoader
private ServiceLoader(Class<S> svc, ClassLoader cl) {
service = Objects.requireNonNull(svc, "Service interface cannot be null");
loader = (cl == null) ? ClassLoader.getSystemClassLoader() : cl;
acc = (System.getSecurityManager() != null) ? AccessController.getContext() : null;
reload();
}
private class LazyIterator
implements Iterator<S>
{
Class<S> service;
ClassLoader loader;
Enumeration<URL> configs = null;
Iterator<String> pending = null;
String nextName = null;
//初始化LazyIterator
private LazyIterator(Class<S> service, ClassLoader loader) {
this.service = service;
this.loader = loader;
}
}
}
ServiceLoader.iterator();獲取迭代器,但其實都是在調(diào)用其內(nèi)部類LazyIterator的迭代器
public final class ServiceLoader<S> implements Iterable<S>{
public Iterator<S> iterator() {
return new Iterator<S>() {
Iterator<Map.Entry<String,S>> knownProviders
= providers.entrySet().iterator();
public boolean hasNext() {
if (knownProviders.hasNext())
return true;
//實際是ServiceLoader內(nèi)部類LazyIterator的hasNext
return lookupIterator.hasNext();
}
public S next() {
if (knownProviders.hasNext())
return knownProviders.next().getValue();
//實際是ServiceLoader內(nèi)部類LazyIterator的next
return lookupIterator.next();
}
public void remove() {
throw new UnsupportedOperationException();
}
};
}
}
LazyIterator的實現(xiàn)
private class LazyIterator implements Iterator<S> {
private boolean hasNextService() {
if (nextName != null) {
return true;
}
if (configs == null) {
//加載文件中內(nèi)容
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;
}
//獲取文件中內(nèi)容
pending = parse(service, configs.nextElement());
}
//賦值元素
nextName = pending.next();
return true;
}
private S nextService() {
//調(diào)用hasNextService判斷是否還有元素
if (!hasNextService())
throw new NoSuchElementException();
String cn = nextName;
nextName = null;
Class<?> c = null;
try {
//根據(jù)實現(xiàn)類權(quán)限定名獲取Class
c = Class.forName(cn, false, loader);
} catch (ClassNotFoundException x) {
fail(service,
"Provider " + cn + " not found");
}
if (!service.isAssignableFrom(c)) {
fail(service,
"Provider " + cn + " not a subtype");
}
try {
//獲取對象
S p = service.cast(c.newInstance());
//緩存對象
providers.put(cn, p);
return p;
} catch (Throwable x) {
fail(service,
"Provider " + cn + " could not be instantiated",
x);
}
throw new Error(); // This cannot happen
}
public boolean hasNext() {
if (acc == null) {
return hasNextService();
} else {
PrivilegedAction<Boolean> action = new PrivilegedAction<Boolean>() {
public Boolean run() { return hasNextService(); }
};
return AccessController.doPrivileged(action, acc);
}
}
public S next() {
if (acc == null) {
return nextService();
} else {
PrivilegedAction<S> action = new PrivilegedAction<S>() {
public S run() { return nextService(); }
};
return AccessController.doPrivileged(action, acc);
}
}
public void remove() {
throw new UnsupportedOperationException();
}
}
開源框架中的實際應(yīng)用:
其中foreach相當(dāng)于調(diào)用iterator,以及hasNext,next