@SPI是了解dubbo源碼的基礎,dubbo-spi是通過jdk-spi優(yōu)化而來的疯兼,對于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這個類纳令,執(zhí)行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;
}
執(zhí)行的步驟:
1挽荠、校驗傳入的class是否為空,為空則拋異常
2平绩、校驗@SPI是否存在
3圈匆、判斷 ConcurrentMap<Class<?>, ExtensionLoader<?>> EXTENSION_LOADERS中是否已經有創(chuàng)建好的ExtensionLoader,如果有則直接獲取捏雌,沒有的話進行代碼創(chuàng)建然后返回對應loader
繼續(xù)跟進代碼跃赚,當我們第一次調用getExtensionLoader()時,map中肯定是不存在對應的value 的性湿,于是我們直接執(zhí)行new ExtensionLoader<T>(type)纬傲;
private ExtensionLoader(Class<?> type) {
this.type = type;
objectFactory = (type == ExtensionFactory.class ? null : ExtensionLoader.getExtensionLoader(ExtensionFactory.class).getAdaptiveExtension());
}
進入上面代碼后我們會進行一次ExtensionFactory的創(chuàng)建,為了將兩個loader區(qū)分開肤频,我們將當前l(fā)oader取名為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
執(zhí)行類似loader1的邏輯后執(zhí)行l(wèi)oader2中的getAdaptiveExtension方法
public T getAdaptiveExtension() {
Object instance = cachedAdaptiveInstance.get();/**首先從緩存中獲取**/
if (instance == null) {/***緩存中不存在的話進行創(chuàng)建*/
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()方法創(chuàng)建對象,執(zhí)行步驟:
1宵荒、獲取class對象并通過反射創(chuàng)建實體
2汁雷、調用injectExtension()方法實現控制反轉
/**
* 1净嘀、通過getAdaptiveExtensionClass()獲取得到需要實例化的class
* 2、通過反射機制實例化對象
* 3侠讯、執(zhí)行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());
}
}
}
}
}
/***省略部分代碼*/
}
執(zhí)行的順序為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集合柴底,并在執(zhí)行getExtension()的時候循環(huán)調用獲取實例。
@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中執(zhí)行該代碼是直接跳過的。
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的執(zhí)行已經完成焙压,我們繼續(xù)跟進loader1的執(zhí)行鸿脓,在loader1的流程中我們在這個時候已經執(zhí)行完畢其構造方法并將對應的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循環(huán)封裝
最終我們通過createExtension返回的其實是一個包裝類绰沥,返回的實體構造如下: