private T createAdaptiveExtension() { try { return injectExtension((T) getAdaptiveExtensionClass().newInstance()); } catch (Exception e) { throw new IllegalStateException("Can not create adaptive extenstion " + type + ", cause: " + e.getMessage(), e); } }
private Class<?> getAdaptiveExtensionClass() { getExtensionClasses(); if (cachedAdaptiveClass != null) { return cachedAdaptiveClass; } return cachedAdaptiveClass = createAdaptiveExtensionClass(); }
ExtensionLoader類的createAdaptiveExtension()方法在前面的 ExtensionFactory的作用 和ExtensionLoader類中的objectFactory分析 都涉及到,當時因為主要是講解IOC功能,所以沒有對createAdaptiveExtension()方法進行細致分析,只是簡單的把源碼的執行過程梳理了下,我們現在就基於之前的分析,再來深入理解一下,先貼出以前的分析成果:
createAdaptiveExtension() 方法執行邏輯:
->getAdaptiveExtensionClass() //下面的調用有兩個分支 // *********** 分支1 ******************* 在找到的類上有Adaptive注解 ->getExtensionClasses() ->loadExtensionClasses() ->loadFile(extensionClasses, DUBBO_INTERNAL_DIRECTORY); injectExtension //完成注入,這是 ExtensionFactory 類的作用之所在 // *********** 分支2 ******************* 在找到的類上沒有Adaptive注解 ->createAdaptiveExtensionClass()
->createAdaptiveExtensionClassCode() //動態生成代碼
->ClassLoader classLoader = findClassLoader();
->com.alibaba.dubbo.common.compiler.Compiler compiler = ExtensionLoader.getExtensionLoader(com.alibaba.dubbo.common.compiler.Compiler.class).getAdaptiveExtension(); //從SPI容器中獲取編譯器Compiler
->return compiler.compile(code, classLoader); //編譯出動態類
injectExtension
從兩個分支來看,分支1是在找在SPI接口的實現類上是否有Adaptive注解的,有的話就返回這個類的Class實例,當分支1的情況不存在的時候,會繼續走分支2 。
分支1的代碼之前有分析,下面看分支2的代碼,着重分析這一句代碼:createAdaptiveExtensionClassCode() , 這句是生成動態類的代碼以供后續的編譯器去編譯
下面是源碼,通過源碼還能發現幾個規則:
(1)就是只有當相應的SPI接口的所有方法上是否有帶Adaptive注解的方法,如果有就會生成動態類的代碼然后進行動態編譯(比如使用javassist框架),如果沒有帶Adaptive注解的方法 ,那就說明該SPI接口是沒有Adaptive性質的實現類的,就會拋出異常
(2)動態類的本質也是在實現相應的SPI接口,它最終也是在調一個現成的SPI實現類來工作,這樣就會有這樣的疑問,那為何不直接指定呢,還非得用動態的呢,呵呵,這就是為什么凡是在方法上出現Adaptive注解的SPI的Adaptive形式都要動態的原因了,因為dubbo這樣一來就可以做到用不同的Adaptive方法,調不同的SPI實現類去處理。
private String createAdaptiveExtensionClassCode() {
StringBuilder codeBuidler = new StringBuilder();
Method[] methods = type.getMethods();
boolean hasAdaptiveAnnotation = false; for(Method m : methods) { if(m.isAnnotationPresent(Adaptive.class)) { hasAdaptiveAnnotation = true; break; } } // 完全沒有Adaptive方法,則不需要生成Adaptive類 if(! hasAdaptiveAnnotation) throw new IllegalStateException("No adaptive method on extension " + type.getName() + ", refuse to create the adaptive class!");
//動態類的包名就是相應的SPI接口的包名
//動態類的類名就 SPI接口名+$Adpative codeBuidler.append("package " + type.getPackage().getName() + ";"); codeBuidler.append("\nimport " + ExtensionLoader.class.getName() + ";"); codeBuidler.append("\npublic class " + type.getSimpleName() + "$Adpative" + " implements " + type.getCanonicalName() + " {"); for (Method method : methods) { Class<?> rt = method.getReturnType(); Class<?>[] pts = method.getParameterTypes(); Class<?>[] ets = method.getExceptionTypes(); Adaptive adaptiveAnnotation = method.getAnnotation(Adaptive.class); StringBuilder code = new StringBuilder(512);
//對於SPI方法上不帶Adaptive注解的方法,生成的方法代碼統統在方法體內拋出UnsupportedOperationException if (adaptiveAnnotation == null) { code.append("throw new UnsupportedOperationException(\"method ") .append(method.toString()).append(" of interface ") .append(type.getName()).append(" is not adaptive method!\");"); } else { int urlTypeIndex = -1; for (int i = 0; i < pts.length; ++i) { if (pts[i].equals(URL.class)) { urlTypeIndex = i; break; } } // 有類型為URL的參數 if (urlTypeIndex != -1) { // Null Point check String s = String.format("\nif (arg%d == null) throw new IllegalArgumentException(\"url == null\");", urlTypeIndex); code.append(s); s = String.format("\n%s url = arg%d;", URL.class.getName(), urlTypeIndex); code.append(s); } // 參數沒有URL類型 else { String attribMethod = null; // 找到參數的URL屬性 LBL_PTS: for (int i = 0; i < pts.length; ++i) { Method[] ms = pts[i].getMethods(); for (Method m : ms) { String name = m.getName(); if ((name.startsWith("get") || name.length() > 3) && Modifier.isPublic(m.getModifiers()) && !Modifier.isStatic(m.getModifiers()) && m.getParameterTypes().length == 0 && m.getReturnType() == URL.class) { urlTypeIndex = i; attribMethod = name; break LBL_PTS; } } } if(attribMethod == null) { throw new IllegalStateException("fail to create adative class for interface " + type.getName() + ": not found url parameter or url attribute in parameters of method " + method.getName()); } // Null point check String s = String.format("\nif (arg%d == null) throw new IllegalArgumentException(\"%s argument == null\");", urlTypeIndex, pts[urlTypeIndex].getName()); code.append(s); s = String.format("\nif (arg%d.%s() == null) throw new IllegalArgumentException(\"%s argument %s() == null\");", urlTypeIndex, attribMethod, pts[urlTypeIndex].getName(), attribMethod); code.append(s); s = String.format("%s url = arg%d.%s();",URL.class.getName(), urlTypeIndex, attribMethod); code.append(s); }
//獲取方法上的Adaptive注解的value值,如果沒有就以SPI接口名做為默認的value,但是會把大寫字母前+".",並轉小寫字母這樣進行處理 String[] value = adaptiveAnnotation.value(); // 沒有設置Key,則使用“擴展點接口名的點分隔 作為Key if(value.length == 0) { char[] charArray = type.getSimpleName().toCharArray(); StringBuilder sb = new StringBuilder(128); for (int i = 0; i < charArray.length; i++) { if(Character.isUpperCase(charArray[i])) { if(i != 0) { sb.append("."); } sb.append(Character.toLowerCase(charArray[i])); } else { sb.append(charArray[i]); } } value = new String[] {sb.toString()}; } boolean hasInvocation = false; for (int i = 0; i < pts.length; ++i) { if (pts[i].getName().equals("com.alibaba.dubbo.rpc.Invocation")) { // Null Point check String s = String.format("\nif (arg%d == null) throw new IllegalArgumentException(\"invocation == null\");", i); code.append(s); s = String.format("\nString methodName = arg%d.getMethodName();", i); code.append(s); hasInvocation = true; break; } }
//cachedDefaultName就是SPI注解中的value值 String defaultExtName = cachedDefaultName; String getNameCode = null; for (int i = value.length - 1; i >= 0; --i) { if(i == value.length - 1) { if(null != defaultExtName) {
//如果SPI注解提供了默認擴展名,且方法的Adaptive注解中的value有 "protocol"
if(!"protocol".equals(value[i])) if (hasInvocation) //方法參數中有com.alibaba.dubbo.rpc.Invocation類型的參數,則方法參數上還應有URL這樣的參數 , 並從url上獲取看是否有 SPI的name參數,如沒有就使用SPI注解的value getNameCode = String.format("url.getMethodParameter(methodName, \"%s\", \"%s\")", value[i], defaultExtName); else getNameCode = String.format("url.getParameter(\"%s\", \"%s\")", value[i], defaultExtName); //意思類似上面,只是獲取的位置不同 else //方法的Adaptive注解上的value沒有"protocol" getNameCode = String.format("( url.getProtocol() == null ? \"%s\" : url.getProtocol() )", defaultExtName); } else { //如果SPI注解上沒提供默認擴展名 if(!"protocol".equals(value[i])) if (hasInvocation) getNameCode = String.format("url.getMethodParameter(methodName, \"%s\", \"%s\")", value[i], defaultExtName); else getNameCode = String.format("url.getParameter(\"%s\")", value[i]); else getNameCode = "url.getProtocol()"; } } else { if(!"protocol".equals(value[i])) if (hasInvocation) getNameCode = String.format("url.getMethodParameter(methodName, \"%s\", \"%s\")", value[i], defaultExtName); else getNameCode = String.format("url.getParameter(\"%s\", %s)", value[i], getNameCode); else getNameCode = String.format("url.getProtocol() == null ? (%s) : url.getProtocol()", getNameCode); } } code.append("\nString extName = ").append(getNameCode).append(";"); // check extName == null? String s = String.format("\nif(extName == null) " + "throw new IllegalStateException(\"Fail to get extension(%s) name from url(\" + url.toString() + \") use keys(%s)\");", type.getName(), Arrays.toString(value)); code.append(s); s = String.format("\n%s extension = (%<s)%s.getExtensionLoader(%s.class).getExtension(extName);", type.getName(), ExtensionLoader.class.getSimpleName(), type.getName()); code.append(s); // return statement if (!rt.equals(void.class)) { code.append("\nreturn "); } s = String.format("extension.%s(", method.getName()); code.append(s); for (int i = 0; i < pts.length; i++) { if (i != 0) code.append(", "); code.append("arg").append(i); } code.append(");"); } codeBuidler.append("\npublic " + rt.getCanonicalName() + " " + method.getName() + "("); for (int i = 0; i < pts.length; i ++) { if (i > 0) { codeBuidler.append(", "); } codeBuidler.append(pts[i].getCanonicalName()); codeBuidler.append(" "); codeBuidler.append("arg" + i); } codeBuidler.append(")"); if (ets.length > 0) { codeBuidler.append(" throws "); for (int i = 0; i < ets.length; i ++) { if (i > 0) { codeBuidler.append(", "); } codeBuidler.append(pts[i].getCanonicalName()); } } codeBuidler.append(" {"); codeBuidler.append(code.toString()); codeBuidler.append("\n}"); } codeBuidler.append("\n}"); if (logger.isDebugEnabled()) { logger.debug(codeBuidler.toString()); } return codeBuidler.toString(); }
下面我們再來看看,如果符合條件,這個動態生成的代碼是個啥樣子的( 以Protocol為例):
public class Protocol$Adpative implements Protocol { public int getDefaultPort() { throw new UnsupportedOperationException( "method public abstract int com.alibaba.dubbo.rpc.Protocol.getDefaultPort() of interface com.alibaba.dubbo.rpc.Protocol is not adaptive method!"); } public <T> Exporter<T> export(Invoker<T> invoker) throws RpcException { if (invoker == null) throw new IllegalArgumentException("com.alibaba.dubbo.rpc.Invoker argument == null"); if (invoker.getUrl() == null) throw new IllegalArgumentException("com.alibaba.dubbo.rpc.Invoker argument getUrl() == null"); com.alibaba.dubbo.common.URL url = invoker.getUrl(); String extName = (url.getProtocol() == null ? "dubbo" : url.getProtocol()); if (extName == null) throw new IllegalStateException("Fail to get extension(com.alibaba.dubbo.rpc.Protocol) name from url(" + url.toString() + ") use keys([protocol])"); com.alibaba.dubbo.rpc.Protocol extension = (com.alibaba.dubbo.rpc.Protocol) ExtensionLoader .getExtensionLoader(com.alibaba.dubbo.rpc.Protocol.class).getExtension(extName); return extension.export(invoker); } public <T> Invoker<T> refer(Class<T> type, URL url1) throws RpcException { if (url1 == null) throw new IllegalArgumentException("url == null"); com.alibaba.dubbo.common.URL url = url1; String extName = (url.getProtocol() == null ? "dubbo" : url.getProtocol()); if (extName == null) throw new IllegalStateException("Fail to get extension(com.alibaba.dubbo.rpc.Protocol) name from url(" + url.toString() + ") use keys([protocol])"); com.alibaba.dubbo.rpc.Protocol extension = (com.alibaba.dubbo.rpc.Protocol) ExtensionLoader .getExtensionLoader(com.alibaba.dubbo.rpc.Protocol.class).getExtension(extName); return extension.refer(type, url1); } public void destroy() { throw new UnsupportedOperationException( "method public abstract void com.alibaba.dubbo.rpc.Protocol.destroy() of interface com.alibaba.dubbo.rpc.Protocol is not adaptive method!"); } }
總結:
1. 獲取某個SPI接口的adaptive實現類的規則是:
(1)實現類的類上面有Adaptive注解的,那么這個類就是adaptive類
(2)實現類的類上面沒有Adaptive注解,但是在方法上有Adaptive注解,則會動態生成adaptive類
2 .生成的動態類的編譯類是:com.alibaba.dubbo.common.compiler.support.AdaptiveCompiler類
3. 動態類的本質是可以做到一個SPI中的不同的Adaptive方法可以去調不同的SPI實現類去處理。使得程序的靈活性大大提高。這才是整套SPI設計的一個精華之所在