Skip to content

Commit ee12b52

Browse files
committed
[U] 更新SPI机制(下)
1 parent d2ee630 commit ee12b52

File tree

1 file changed

+37
-1
lines changed

1 file changed

+37
-1
lines changed

note/Dubbo/Dubbo底层源码学习(二)—— Dubbo的SPI机制(下).md

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,43 @@ Dubbo SPI的核心逻辑几乎都封装在ExtensionLoader之中,ExtensionLoade
2525

2626
下面展示了ExtensionLoader最常用的使用方式:
2727
```
28-
SimpleExt ext = getExtensionLoader(SimpleExt.class).getDefaultExtension();
28+
SimpleExt ext = ExtensionLoader.getExtensionLoader(SimpleExt.class).getDefaultExtension();
29+
```
30+
31+
首先时调用ExtensionLoader#getExtensionLoader(SimpleExt.class),来获取SimpleExt类型的ExtensionLoader。查看ExtensionLoader源码如下:
32+
33+
```
34+
public static <T> ExtensionLoader<T> getExtensionLoader(Class<T> type) {
35+
if (type == null) {
36+
throw new IllegalArgumentException("Extension type == null");
37+
}
38+
if (!type.isInterface()) {
39+
throw new IllegalArgumentException("Extension type (" + type + ") is not an interface!");
40+
}
41+
if (!withExtensionAnnotation(type)) {
42+
throw new IllegalArgumentException("Extension type (" + type +
43+
") is not an extension, because it is NOT annotated with @" + SPI.class.getSimpleName() + "!");
44+
}
45+
46+
ExtensionLoader<T> loader = (ExtensionLoader<T>) EXTENSION_LOADERS.get(type);
47+
if (loader == null) {
48+
// 如果初始指定的EXTENSION_LOADER为空值,则新new一个ExtensionLoader对象存放至其中。要注意ExtensionLoader的构造方法内容!
49+
EXTENSION_LOADERS.putIfAbsent(type, new ExtensionLoader<T>(type));
50+
loader = (ExtensionLoader<T>) EXTENSION_LOADERS.get(type);
51+
}
52+
return loader;
53+
}
54+
```
55+
getExtensionLoader方法首先回去判断EXTENSION_LOADERS缓存中是否已经缓存了该类型的扩展点加载器,如果没有则new一个该类型的ExtensionLoader并添加进EXTENSION_LOADERS中。但需要注意的是ExtensionLoader的构造方法
56+
中,是会先创建默认的ExtensionFactory类型的ExtensionLoader对象,然后调用getAdaptiveExtension()方法创建适配类型的扩展点实现类。
57+
58+
```
59+
private ExtensionLoader(Class<?> type) {
60+
this.type = type;
61+
// 从此处可以知道,对于默认的ExtensionFactory.class来说,是没有objectFactory熟悉对象值的
62+
// 如果type不为ExtensionFactory类型的,则会创建一个ExtensionFactory的适配工厂来成为objectFactory对象属性
63+
objectFactory = (type == ExtensionFactory.class ? null : ExtensionLoader.getExtensionLoader(ExtensionFactory.class).getAdaptiveExtension());
64+
}
2965
```
3066

3167

0 commit comments

Comments
 (0)