在上一篇文章:Java SPI(Service Provider Interface)簡介 中對Java SPI機製做了簡單說明,並附上了一個具體的demo。對Java SPI不熟悉的同學可以去參閱一下那篇文章,本文不再贅述。
本文將在上一篇文章的基礎之上,結合JDK 1.7 源碼來剖析Java SPI的內部實現原理。
在上一篇文章中,我們通過如下代碼擷取Service的具體實現,代碼如下:
import java.util.Iterator;import java.util.ServiceLoader;import com.ricky.codelab.spi.DemoService;//1.ServiceLoader.loadServiceLoader<DemoService> serviceLoader = ServiceLoader.load(DemoService.class);//2.serviceLoader.iterator()Iterator<DemoService> it = serviceLoader.iterator();//3.hasNext()while (it.hasNext()) { //4.next() DemoService demoService = it.next();}1、ServiceLoader.load方法
首先來看看ServiceLoader.load方法,如下:
public static <S> ServiceLoader<S> load(Class<S> service) { ClassLoader cl = Thread.currentThread().getContextClassLoader(); return ServiceLoader.load(service, cl);}
它有一個重載方法,如下:
public static <S> ServiceLoader<S> load(Class<S> service, ClassLoader loader){ return new ServiceLoader<>(service, loader);}
這裡通過調用 new ServiceLoader<>(service, loader)返回一個ServiceLoader執行個體對象,ServiceLoader<>(service, loader)構造方法如下:
private ServiceLoader(Class<S> svc, ClassLoader cl) { service = svc; loader = cl; reload();}
構造方法內部調用了reload方法,如下:
public void reload() { providers.clear(); lookupIterator = new LazyIterator(service, loader);}
providers、lookupIterator 屬性定義如下:
// The class loader used to locate, load, and instantiate providersprivate ClassLoader loader;// Cached providers, in instantiation orderprivate LinkedHashMap<String,S> providers = new LinkedHashMap<>();// The current lazy-lookup iteratorprivate LazyIterator lookupIterator;
接下來看看ServiceLoader內部類LazyIterator的實現代碼,如下:
// Private inner class implementing fully-lazy provider lookup//private class LazyIterator implements Iterator<S>{ Class<S> service; ClassLoader loader; Enumeration<URL> configs = null; Iterator<String> pending = null; String nextName = null; private LazyIterator(Class<S> service, ClassLoader loader) { this.service = service; this.loader = loader; } public boolean hasNext() { 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; } public S next() { if (!hasNext()) { throw new NoSuchElementException(); } String cn = nextName; nextName = null; Class<?> c = null; try { 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 void remove() { throw new UnsupportedOperationException(); }}
其中,PREFIX 定義如下:
private static final String PREFIX = "META-INF/services/";
2、ServiceLoader iterator方法
當執行 Iterator it = serviceLoader.iterator(); 代碼時,執行的是ServiceLoader iterator方法,代碼如下:
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; return lookupIterator.hasNext(); } public S next() { if (knownProviders.hasNext()) return knownProviders.next().getValue(); return lookupIterator.next(); } public void remove() { throw new UnsupportedOperationException(); } };}
返回了一個Iterator的匿名類, Iterator hasNext()方法
while (it.hasNext()) {
DemoService demoService = it.next();
}
it.hasNext()調用的是上述返回的 new Iterator ()的public boolean hasNext()方法。 Iterator next方法
it.next();調用的是上述返回的 new Iterator ()的public S next() 方法。