@SPI是了解dubbo源码的基础,dubbo-spi是通过jdk-spi优化而来的,对于jdk-spi的原理这里不做过多解释,有兴趣的童鞋可以自行百度。
对于@SPI的使用可以通过以下代码的跟踪来进行相关了解。
ExtensionLoader<WrappedExt> loader = ExtensionLoader.getExtensionLoader(WrappedExt.class);
WrappedExt impl1 = loader.getExtension("impl1");
首先我们可以先看WrappedExt 这个类
@SPI("impl1")
public interface WrappedExt {
String echo(URL url, String s);
}
首先我们可以找到在resouce-META-INF文件夹下可以找到对应的一个配置文件“com.alibaba.dubbo.common.extensionloader.ext6_wrap.WrappedExt”,里面的内容如下:
impl1=com.alibaba.dubbo.common.extensionloader.ext6_wrap.impl.Ext5Impl1
impl2=com.alibaba.dubbo.common.extensionloader.ext6_wrap.impl.Ext5Impl2
wrapper1=com.alibaba.dubbo.common.extensionloader.ext6_wrap.impl.Ext5Wrapper1
wrapper2=com.alibaba.dubbo.common.extensionloader.ext6_wrap.impl.Ext5Wrapper2
在WrappedExt 接口中我们可以看出@SPI标签默认实现的是key=‘impl1’对应的class。
OK,让我们开始对前面的第一行代码ExtensionLoader<WrappedExt> loader = ExtensionLoader.getExtensionLoader(WrappedExt.class);进行解析,首先我们进入ExtensionLoader这个类,执行getExtensionLoader()方法代码如下:
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!");
}
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;
}
执行的步骤:
1、校验传入的class是否为空,为空则抛异常
2、校验@SPI是否存在
3、判断 ConcurrentMap<Class<?>, ExtensionLoader<?>> EXTENSION_LOADERS中是否已经有创建好的ExtensionLoader,如果有则直接获取,没有的话进行代码创建然后返回对应loader
继续跟进代码,当我们第一次调用getExtensionLoader()时,map中肯定是不存在对应的value 的,于是我们直接执行new ExtensionLoader<T>(type);
private ExtensionLoader(Class<?> type) {
this.type = type;
objectFactory = (type == ExtensionFactory.class ? null : ExtensionLoader.getExtensionLoader(ExtensionFactory.class).getAdaptiveExtension());
}
进入上面代码后我们会进行一次ExtensionFactory的创建,为了将两个loader区分开,我们将当前loader取名为loader1,ExtensionFactory对应的loader取名为loader2
/**
* ExtensionFactory
*/
@SPI
public interface ExtensionFactory {
/**
* Get extension.
*
* @param type object type.
* @param name object name.
* @return object instance.
*/
<T> T getExtension(Class<T> type, String name);
}
adaptive=com.alibaba.dubbo.common.extension.factory.AdaptiveExtensionFactory
spi=com.alibaba.dubbo.common.extension.factory.SpiExtensionFactory
执行类似loader1的逻辑后执行loader2中的getAdaptiveExtension方法
public T getAdaptiveExtension() {
Object instance = cachedAdaptiveInstance.get();/**首先从缓存中获取**/
if (instance == null) {/***缓存中不存在的话进行创建*/
if (createAdaptiveInstanceError == null) {
synchronized (cachedAdaptiveInstance) {
instance = cachedAdaptiveInstance.get();
if (instance == null) {
try {
instance = createAdaptiveExtension();
cachedAdaptiveInstance.set(instance);
} catch (Throwable t) {
createAdaptiveInstanceError = t;
throw new IllegalStateException("fail to create adaptive instance: " + t.toString(), t);
}
}
}
} else {
throw new IllegalStateException("fail to create adaptive instance: " + createAdaptiveInstanceError.toString(), createAdaptiveInstanceError);
}
}
return (T) instance;
}
通过createAdaptiveExtension()方法创建对象,执行步骤:
1、获取class对象并通过反射创建实体
2、调用injectExtension()方法实现控制反转
/**
* 1、通过getAdaptiveExtensionClass()获取得到需要实例化的class
* 2、通过反射机制实例化对象
* 3、执行injectExtension()实现控制反转
*/
private T createAdaptiveExtension() {
try {
return injectExtension((T) getAdaptiveExtensionClass().newInstance());
} catch (Exception e) {
throw new IllegalStateException("Can not create adaptive extension " + type + ", cause: " + e.getMessage(), e);
}
}
private Class<?> getAdaptiveExtensionClass() {
getExtensionClasses();
if (cachedAdaptiveClass != null) {
return cachedAdaptiveClass;
}
return cachedAdaptiveClass = createAdaptiveExtensionClass();
}
/**首先从缓存获取class,如果没有则调用loadExtensionClasses()*/
private Map<String, Class<?>> getExtensionClasses() {
Map<String, Class<?>> classes = cachedClasses.get();
if (classes == null) {
synchronized (cachedClasses) {
classes = cachedClasses.get();
if (classes == null) {
classes = loadExtensionClasses();
cachedClasses.set(classes);
}
}
}
return classes;
}
private Map<String, Class<?>> loadExtensionClasses() {
final SPI defaultAnnotation = type.getAnnotation(SPI.class);
if (defaultAnnotation != null) {
String value = defaultAnnotation.value();
if (value != null && (value = value.trim()).length() > 0) {
String[] names = NAME_SEPARATOR.split(value);
if (names.length > 1) {
throw new IllegalStateException("more than 1 default extension name on extension " + type.getName()
+ ": " + Arrays.toString(names));
}
if (names.length == 1) cachedDefaultName = names[0];
}
}
Map<String, Class<?>> extensionClasses = new HashMap<String, Class<?>>();
loadFile(extensionClasses, DUBBO_INTERNAL_DIRECTORY);
loadFile(extensionClasses, DUBBO_DIRECTORY);
loadFile(extensionClasses, SERVICES_DIRECTORY);
return extensionClasses;
}
private void loadFile(Map<String, Class<?>> extensionClasses, String dir) {
/***通过dir路径获取对应的class,部分代码省略*/
Class<?> clazz = Class.forName(line, true, classLoader);
if (!type.isAssignableFrom(clazz)) {
throw new IllegalStateException("Error when load extension class(interface: " +
type + ", class line: " + clazz.getName() + "), class "
+ clazz.getName() + "is not subtype of interface.");
}
if (clazz.isAnnotationPresent(Adaptive.class)) {//当对应class存在@Adaptive时放置进入缓存对象
if (cachedAdaptiveClass == null) {
cachedAdaptiveClass = clazz;
} else if (!cachedAdaptiveClass.equals(clazz)) {
throw new IllegalStateException("More than 1 adaptive class found: "
+ cachedAdaptiveClass.getClass().getName()
+ ", " + clazz.getClass().getName());
}
} else {
try {
clazz.getConstructor(type);//如果存在以父类interface为参数的构造方法时,将class放入cachedWrapperClasses缓存对象
Set<Class<?>> wrappers = cachedWrapperClasses;
if (wrappers == null) {
cachedWrapperClasses = new ConcurrentHashSet<Class<?>>();
wrappers = cachedWrapperClasses;
}
wrappers.add(clazz);
} catch (NoSuchMethodException e) {
clazz.getConstructor();
if (name == null || name.length() == 0) {
name = findAnnotationName(clazz);
if (name == null || name.length() == 0) {
if (clazz.getSimpleName().length() > type.getSimpleName().length()
&& clazz.getSimpleName().endsWith(type.getSimpleName())) {
name = clazz.getSimpleName().substring(0, clazz.getSimpleName().length() - type.getSimpleName().length()).toLowerCase();
} else {
throw new IllegalStateException("No such extension name for the class " + clazz.getName() + " in the config " + url);
}
}
}
String[] names = NAME_SEPARATOR.split(name);
if (names != null && names.length > 0) {
Activate activate = clazz.getAnnotation(Activate.class);
if (activate != null) {
cachedActivates.put(names[0], activate);
}
for (String n : names) {
if (!cachedNames.containsKey(clazz)) {
cachedNames.put(clazz, n);
}
Class<?> c = extensionClasses.get(n);
if (c == null) {
extensionClasses.put(n, clazz);
} else if (c != clazz) {
throw new IllegalStateException("Duplicate extension " + type.getName() + " name " + n + " on " + c.getName() + " and " + clazz.getName());
}
}
}
}
}
/***省略部分代码*/
}
执行的顺序为createAdaptiveExtension()-->getAdaptiveExtensionClass()-->getExtensionClasses() -->loadExtensionClasses()得到对应的class类"spi" -> "class com.alibaba.dubbo.common.extension.factory.SpiExtensionFactory"放入cachedClasses缓存,然后在getAdaptiveExtensionClass()方法中通过判断获取到AdaptiveClass->com.alibaba.dubbo.common.extension.factory.AdaptiveExtensionFactory。
接下来我们来看AdaptiveExtensionFactory这个对象的实例化代码,在其构造方法中会将获取得到的ExtensionFactory放入factories集合,并在执行getExtension()的时候循环调用获取实例。
@Adaptive
public class AdaptiveExtensionFactory implements ExtensionFactory {
private final List<ExtensionFactory> factories;
public AdaptiveExtensionFactory() {
ExtensionLoader<ExtensionFactory> loader = ExtensionLoader.getExtensionLoader(ExtensionFactory.class);
List<ExtensionFactory> list = new ArrayList<ExtensionFactory>();
for (String name : loader.getSupportedExtensions()) {
list.add(loader.getExtension(name));
}
factories = Collections.unmodifiableList(list);
}
public <T> T getExtension(Class<T> type, String name) {
for (ExtensionFactory factory : factories) {
T extension = factory.getExtension(type, name);
if (extension != null) {
return extension;
}
}
return null;
}
}
调用injectExtension()进行控制反转,因为loader2中的objectFactory其实是为null的,所以在loader2中执行该代码是直接跳过的。
private T injectExtension(T instance) {
try {
if (objectFactory != null) {
for (Method method : instance.getClass().getMethods()) {
if (method.getName().startsWith("set")
&& method.getParameterTypes().length == 1
&& Modifier.isPublic(method.getModifiers())) {
Class<?> pt = method.getParameterTypes()[0];
try {
String property = method.getName().length() > 3 ? method.getName().substring(3, 4).toLowerCase() + method.getName().substring(4) : "";
Object object = objectFactory.getExtension(pt, property);
if (object != null) {
method.invoke(instance, object);
}
} catch (Exception e) {
logger.error("fail to inject via method " + method.getName()
+ " of interface " + type.getName() + ": " + e.getMessage(), e);
}
}
}
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
return instance;
}
在此loader2的执行已经完成,我们继续跟进loader1的执行,在loader1的流程中我们在这个时候已经执行完毕其构造方法并将对应的objectFactory放入缓存对象即AdaptiveExtensionFactory并在getExtensionLoader()中返回loader1。
接着我们跟进代码WrappedExt impl1 = loader.getExtension("impl1");
/**
* 1、判断name是否存在,不存在的话则返回spi中设置的vlaue值
* 2、根据name进行实例化
*/
public T getExtension(String name) {
if (name == null || name.length() == 0)
throw new IllegalArgumentException("Extension name == null");
if ("true".equals(name)) {
return getDefaultExtension();
}
Holder<Object> holder = cachedInstances.get(name);
if (holder == null) {
cachedInstances.putIfAbsent(name, new Holder<Object>());
holder = cachedInstances.get(name);
}
Object instance = holder.get();
if (instance == null) {
synchronized (holder) {
instance = holder.get();
if (instance == null) {
instance = createExtension(name);
holder.set(instance);
}
}
}
return (T) instance;
}
/**
* 1、通过反射获取实体
* 2、进行wrapper包装
*
*/
private T createExtension(String name) {
Class<?> clazz = getExtensionClasses().get(name);
if (clazz == null) {
throw findException(name);
}
try {
T instance = (T) EXTENSION_INSTANCES.get(clazz);
if (instance == null) {
EXTENSION_INSTANCES.putIfAbsent(clazz, (T) clazz.newInstance());
instance = (T) EXTENSION_INSTANCES.get(clazz);
}
injectExtension(instance);
Set<Class<?>> wrapperClasses = cachedWrapperClasses;
if (wrapperClasses != null && wrapperClasses.size() > 0) {
for (Class<?> wrapperClass : wrapperClasses) {
instance = injectExtension((T) wrapperClass.getConstructor(type).newInstance(instance));
}
}
return instance;
} catch (Throwable t) {
throw new IllegalStateException("Extension instance(name: " + name + ", class: " +
type + ") could not be instantiated: " + t.getMessage(), t);
}
}
由之前的代码我们可以的到在loadFile()方法中我们会将两个封装用的类wrapper1与wrapper2放入cachedWrapperClasses中,然后进行for循环封装
最终我们通过createExtension返回的其实是一个包装类,返回的实体构造如下: