SPI 全称为(Service Provider Interface),是JDK内置的一种服务提供发现机制。一个服务(Service)通常指的是已知的接口或者抽象类,服务提供方就是对这个接口或者抽象类的实现,然后按照SPI 标准存放到资源路径META-INF/services目录下,文件的命名为该服务接口的全限定名。
有这么一个服务
package com.zto.sxy.helloworld;
public interface ISPI {
void say();
}
实现类SPITestA
package com.zto.sxy.helloworld;
public class SPITestA implements ISPI{
@Override
public void say() {
System.out.println("SPI with implement testA");
}
}
实现类SPITestB
package com.zto.sxy.helloworld;
public class SPITestB implements ISPI{
@Override
public void say() {
System.out.println("SPI with implement testB");
}
}
然后在resources目录下添加META-INF/services文件夹,同时新建一个名为com.zto.sxy.helloworld.ISPI的文件,内容如下:
com.zto.sxy.helloworld.SPITestA
com.zto.sxy.helloworld.SPITestB
以下是测试类
public class TestSPI {
@Test
public void testWithNoSPI(){
ISPI testA = new SPITestA();
testA.say();
ISPI testB = new SPITestB();
testB.say();
}
@Test
public void testWithSPI(){
ServiceLoader services = ServiceLoader.load(ISPI.class);
for (Iterator<ISPI> iterator = services.iterator(); iterator.hasNext(); ) {
ISPI spi = iterator.next();
spi.say();
}
}
}
执行测试函数,发现两个输出结果一样,说明SPI生效了,输出结果如下:
SPI with implement testA
SPI with implement testB
先看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);
}
private ServiceLoader(Class<S> svc, ClassLoader cl) {
// 确保Class参数不为空
service = Objects.requireNonNull(svc, "Service interface cannot be null");
loader = (cl == null) ? ClassLoader.getSystemClassLoader() : cl;
acc = (System.getSecurityManager() != null) ? AccessController.getContext() : null;
// 清空缓存,确保会重新加载
reload();
}
在调用的的时候,先通过调用iterator方法返回一个Iterator对象,然后遍历该Iterator对象
public Iterator<S> iterator() {
return new Iterator<S>() {
// private LinkedHashMap<String,S> providers = new LinkedHashMap<>();
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();
}
};
}
调用hasNext方法的时候,会调用lookupIterator.hasNext()
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;
}
当调用next方法的时候
private S nextService() {
if (!hasNextService())
throw new NoSuchElementException();
String cn = nextName;
nextName = null;
Class<?> c = null;
try {
// 生成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
}
ServiceLoader不是一实例化以后立马就去读配置文件中的服务实现者并实例化,而是等其Iterator实现获取对应的服务提供者时才会加载对应的配置文件进行解析,在调用Iterator的hasNext方法时会去加载配置文件进行解析,在调用next方法时会将对应的服务提供者进行实例化并进行缓存。
Dubbo基于Java SPI机制,在其基础上做了改进和扩展,其实现类是ExtensionLoader。
@Test
public void test(){
Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getExtension("dubbo");
protocol.destroy();
}
先看看getExtensionLoader静态方法
// 缓存的是扩展和ExtensionLoader实例的关系,每一种扩展对应一个ExtensionLoader实例
private static final ConcurrentMap<Class<?>, ExtensionLoader<?>> EXTENSION_LOADERS = new ConcurrentHashMap<>();
// 缓存的是扩展实现类
private static final ConcurrentMap<Class<?>, Object> EXTENSION_INSTANCES = new ConcurrentHashMap<>();
public static <T> ExtensionLoader<T> getExtensionLoader(Class<T> type) {
if (type == null)
throw new IllegalArgumentException("Extension type == null");
if (!type.isInterface()) {
throw new IllegalArgumentException("Extension type(" + type + ") is not interface!");
}
// 检查是否有@SPI注解
if (!withExtensionAnnotation(type)) {
throw new IllegalArgumentException("Extension type(" + type +
") is not extension, because WITHOUT @" + SPI.class.getSimpleName() + " Annotation!");
}
ExtensionLoader<T> loader = (ExtensionLoader<T>) EXTENSION_LOADERS.get(type);
if (loader == null) {
EXTENSION_LOADERS.putIfAbsent(type, new ExtensionLoader<T>(type));
loader = (ExtensionLoader<T>) EXTENSION_LOADERS.get(type);
}
return loader;
}