1.首先我们创建一些类,我们再一步一步的进行分析dubbo的扩展点的源代码
public class DefaultExtensionImpl implements MyInterface {
@Override
public String sayHello(String name, String type) {
return this.getClass().getName() + " " + name + " " + type;
}
}
public class ExtensionTest {
@SuppressWarnings("rawtypes")
public static void main(String[] args) {
System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
ExtensionLoader extensionLoader = ExtensionLoader
.getExtensionLoader(MyInterface.class);
MyInterface myFirstExtension = (MyInterface) extensionLoader
.getAdaptiveExtension();
System.out.println(myFirstExtension.sayHello("xxx",
ExtensionType.defaults));
}
}
public class ExtensionType {
public static final String defaults = "defaults";
public static final String other = "other";
}
@Adaptive
public class MyAdaptiveExtension implements MyInterface {
@SuppressWarnings("rawtypes")
@Override
public String sayHello(String name, String type) {
ExtensionLoader extensionLoader = ExtensionLoader
.getExtensionLoader(MyInterface.class);
MyInterface extension = (MyInterface) extensionLoader
.getDefaultExtension();
if (ExtensionType.defaults.equals(type)) {
extension = (MyInterface) extensionLoader
.getExtension("defaults");
}
if (ExtensionType.other.equals(type)) {
extension = (MyInterface) extensionLoader
.getExtension("other");
}
return extension.sayHello(name, type);
}
}
@SPI("defaults")
public interface MyInterface {
public String sayHello(String name, String type);
}
public class OtherExtensionImpl implements MyInterface {
@Override
public String sayHello(String name, String type) {
return this.getClass().getName() + " " + name + " " + type;
}
}
com.alibaba.dubbo.demo.extensiontest.MyInterface内容:
defaults=com.alibaba.dubbo.demo.extensiontest.DefaultExtensionImpl
other=com.alibaba.dubbo.demo.extensiontest.OtherExtensionImpl
adaptive=com.alibaba.dubbo.demo.extensiontest.MyAdaptiveExtension
运行的结果
2.现在需要创建一个ExtensionLoader对象 ,ExtensionLoader是个单例,但是提供了一个getExtensionLoader方法
@SuppressWarnings("unchecked")
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!");
}
// 先从EXTENSION_LOADERS获取ExtensionLoader
ExtensionLoader<T> loader = (ExtensionLoader<T>) EXTENSION_LOADERS
.get(type);
// 新建一个ExtensionLoader对象
if (loader == null) {
EXTENSION_LOADERS.putIfAbsent(type, new ExtensionLoader<T>(type));
loader = (ExtensionLoader<T>) EXTENSION_LOADERS.get(type);
}
return loader;
}
3.创建一个ExtensionLoader对象
private ExtensionL