SPI实现原理介绍
作者:互联网
SPI实现原理介绍
SericeLoader
从JAVA中的SPI实践学习中了解到查找实现的一个重要方法为:
ServiceLoader shouts = ServiceLoader.load(Handler.class);
其类结构为:
public final class ServiceLoader<S>
implements Iterable<S>
{
//SPI配置文件所有路径
private static final String PREFIX = "META-INF/services/";
// The class or interface representing the service being loaded
private final Class<S> service;
// The class loader used to locate, load, and instantiate providers
private final ClassLoader loader;
// The access control context taken when the ServiceLoader is created
private final AccessControlContext acc;
// Cached providers, in instantiation order
private LinkedHashMap<String,S> providers = new LinkedHashMap<>();
// The current lazy-lookup iterator
private LazyIterator lookupIterator;
Load方法
是直接实例化了一个ServiceLoader,参考:
return new ServiceLoader<>(service, loader);
在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();
}
reload
public void reload() {
providers.clear();
lookupIterator = new LazyIterator(service, loader);
}
查找实现类
查找实现类和创建实现类的过程,都在LazyIterator完成。当我们调用iterator.hasNext和iterator.next方法的时候,实际上调用的都是LazyIterator的相应方法。
List handlers = Lists.newArrayList(shouts.iterator());
ServiceLoader shouts = ServiceLoader.load(Animal.class);
for (Animal s : shouts) {
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方法的时候,实际调用到的是,lookupIterator.nextService。它通过反射的方式,创建实现类的实例并返回。
private S nextService() {
if (!hasNextService())
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
}
next---->nextService----->hasNextService---->class.forName
标签:cn,service,介绍,loader,SPI,private,原理,null,ServiceLoader 来源: https://blog.csdn.net/sunquan291/article/details/101150277