// 创建 extensionprivateTcreateExtension(Stringname,booleanwrap){// 获取扩展的 class, 读取 META-INF/dubbo/internal, META-INF/services, META-INF/dubbo 目录下Class<?>clazz=getExtensionClasses().get(name);if(clazz==null||unacceptableExceptions.contains(name)){throwfindException(name);}try{// 从缓存中获取对象Tinstance=(T)extensionInstances.get(clazz);if(instance==null){// 创建 extension 实例extensionInstances.putIfAbsent(clazz,createExtensionInstance(clazz));instance=(T)extensionInstances.get(clazz);instance=postProcessBeforeInitialization(instance,name);// 注入属性injectExtension(instance);instance=postProcessAfterInitialization(instance,name);}if(wrap){List<Class<?>>wrapperClassesList=newArrayList<>();if(cachedWrapperClasses!=null){wrapperClassesList.addAll(cachedWrapperClasses);wrapperClassesList.sort(WrapperComparator.COMPARATOR);Collections.reverse(wrapperClassesList);}if(CollectionUtils.isNotEmpty(wrapperClassesList)){// 遍历包装类for(Class<?>wrapperClass:wrapperClassesList){Wrapperwrapper=wrapperClass.getAnnotation(Wrapper.class);booleanmatch=(wrapper==null)||((ArrayUtils.isEmpty(wrapper.matches())||ArrayUtils.contains(wrapper.matches(),name))&&!ArrayUtils.contains(wrapper.mismatches(),name));if(match){// 注入类instance=injectExtension((T)wrapperClass.getConstructor(type).newInstance(instance));instance=postProcessAfterInitialization(instance,name);}}}}// Warning: After an instance of Lifecycle is wrapped by cachedWrapperClasses, it may not still be Lifecycle instance, this application may not invoke the lifecycle.initialize hook.// 初始化 extensioninitExtension(instance);returninstance;}catch(Throwablet){thrownewIllegalStateException("Extension instance (name: "+name+", class: "+type+") couldn't be instantiated: "+t.getMessage(),t);}}
// loadClass privatevoidloadClass(ClassLoaderclassLoader,Map<String,Class<?>>extensionClasses,java.net.URLresourceURL,Class<?>clazz,Stringname,booleanoverridden){if(!type.isAssignableFrom(clazz)){thrownewIllegalStateException("Error occurred when loading extension class (interface: "+type+", class line: "+clazz.getName()+"), class "+clazz.getName()+" is not subtype of interface.");}booleanisActive=loadClassIfActive(classLoader,clazz);if(!isActive){return;}if(clazz.isAnnotationPresent(Adaptive.class)){// 缓存 Adaptive classcacheAdaptiveClass(clazz,overridden);}elseif(isWrapperClass(clazz)){// 缓存 Wrapper classcacheWrapperClass(clazz);}else{if(StringUtils.isEmpty(name)){name=findAnnotationName(clazz);if(name.length()==0){thrownewIllegalStateException("No such extension name for the class "+clazz.getName()+" in the config "+resourceURL);}}String[]names=NAME_SEPARATOR.split(name);if(ArrayUtils.isNotEmpty(names)){// 缓存 Activate classcacheActivateClass(clazz,names[0]);for(Stringn:names){cacheName(clazz,n);saveInExtensionClass(extensionClasses,clazz,n,overridden);}}}}
// 获取 ActivatepublicList<T>getActivateExtension(URLurl,String[]values,Stringgroup){checkDestroyed();// solve the bug of using @SPI's wrapper method to report a null pointer exception.Map<Class<?>,T>activateExtensionsMap=newTreeMap<>(activateComparator);List<String>names=values==null?newArrayList<>(0):Arrays.stream(values).map(StringUtils::trim).collect(Collectors.toList());Set<String>namesSet=newHashSet<>(names);// 判断是否移除默认的if(!namesSet.contains(REMOVE_VALUE_PREFIX+DEFAULT_KEY)){if(cachedActivateGroups.size()==0){synchronized(cachedActivateGroups){// cache all extensionsif(cachedActivateGroups.size()==0){// 确保 extension 已经加载,这个方法上面已经分析过了getExtensionClasses();// 遍历所有的 activate classfor(Map.Entry<String,Object>entry:cachedActivates.entrySet()){Stringname=entry.getKey();Objectactivate=entry.getValue();String[]activateGroup,activateValue;// 获取 @Activate 的 group 和 valueif(activateinstanceofActivate){activateGroup=((Activate)activate).group();activateValue=((Activate)activate).value();}elseif(activateinstanceofcom.alibaba.dubbo.common.extension.Activate){activateGroup=((com.alibaba.dubbo.common.extension.Activate)activate).group();activateValue=((com.alibaba.dubbo.common.extension.Activate)activate).value();}else{continue;}cachedActivateGroups.put(name,newHashSet<>(Arrays.asList(activateGroup)));String[][]keyPairs=newString[activateValue.length][];for(inti=0;i<activateValue.length;i++){if(activateValue[i].contains(":")){keyPairs[i]=newString[2];String[]arr=activateValue[i].split(":");keyPairs[i][0]=arr[0];keyPairs[i][1]=arr[1];}else{keyPairs[i]=newString[1];keyPairs[i][0]=activateValue[i];}}// 加入到缓存中cachedActivateValues.put(name,keyPairs);}}}}// traverse all cached extensionscachedActivateGroups.forEach((name,activateGroup)->{// 判断 group 和 name 是否匹配if(isMatchGroup(group,activateGroup)&&!namesSet.contains(name)&&!namesSet.contains(REMOVE_VALUE_PREFIX+name)&&isActive(cachedActivateValues.get(name),url)){// 保存默认的 activateactivateExtensionsMap.put(getExtensionClass(name),getExtension(name));}});}// 有默认的配置, 组合 activateif(namesSet.contains(DEFAULT_KEY)){// will affect order// `ext1,default,ext2` means ext1 will happens before all of the default extensions while ext2 will after themArrayList<T>extensionsResult=newArrayList<>(activateExtensionsMap.size()+names.size());for(Stringname:names){if(name.startsWith(REMOVE_VALUE_PREFIX)||namesSet.contains(REMOVE_VALUE_PREFIX+name)){continue;}if(DEFAULT_KEY.equals(name)){extensionsResult.addAll(activateExtensionsMap.values());continue;}if(containsExtension(name)){extensionsResult.add(getExtension(name));}}returnextensionsResult;}else{// add extensions, will be sorted by its orderfor(Stringname:names){if(name.startsWith(REMOVE_VALUE_PREFIX)||namesSet.contains(REMOVE_VALUE_PREFIX+name)){continue;}if(DEFAULT_KEY.equals(name)){continue;}if(containsExtension(name)){activateExtensionsMap.put(getExtensionClass(name),getExtension(name));}}returnnewArrayList<>(activateExtensionsMap.values());}}
// 动态创建privateClass<?>createAdaptiveExtensionClass(){// Adaptive Classes' ClassLoader should be the same with Real SPI interface classes' ClassLoaderClassLoaderclassLoader=type.getClassLoader();try{if(NativeUtils.isNative()){returnclassLoader.loadClass(type.getName()+"$Adaptive");}}catch(Throwableignore){}// 生成代码Stringcode=newAdaptiveClassCodeGenerator(type,cachedDefaultName).generate();org.apache.dubbo.common.compiler.Compilercompiler=extensionDirector.getExtensionLoader(org.apache.dubbo.common.compiler.Compiler.class).getAdaptiveExtension();// 编译代码,然后加载returncompiler.compile(type,code,classLoader);}