public static void main(String[] args) {
ExtensionLoader<TodayService> loader = ExtensionLoader.getExtensionLoader(TodayService.class);
TodayService happy = loader.getExtension("happy");
happy.soul();
}
扩展点加载器如果根据扩展名加载扩展类
- org.apache.dubbo.common.extension.ExtensionLoader#getExtension
public T getExtension(String name) {
// 参数校验
if (StringUtils.isEmpty(name)) {
throw new IllegalArgumentException("Extension name == null");
}
if ("true".equals(name)) {
return getDefaultExtension();
}
// 一个引用对象,来创建实例
final Holder<Object> holder = getOrCreateHolder(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;
}
- org.apache.dubbo.common.extension.ExtensionLoader#createExtension
private T createExtension(String name) {
// 根据name 或获取Class,用于创建实例
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, clazz.newInstance());
instance = (T) EXTENSION_INSTANCES.get(clazz);
}
injectExtension(instance);
Set<Class<?>> wrapperClasses = cachedWrapperClasses;
if (CollectionUtils.isNotEmpty(wrapperClasses)) {
for (Class<?> wrapperClass : wrapperClasses) {
instance = injectExtension((T) wrapperClass.getConstructor(type).newInstance(instance));
}
}
initExtension(instance);
return instance;
} catch (Throwable t) {
throw new IllegalStateException("Extension instance (name: " + name + ", class: " +
type + ") couldn't be instantiated: " + t.getMessage(), t);
}
}