spi機制的思想提供一種更加靈活的,可插拔式的機制。本文分別對比了java和dubbo的spi的實現的區別,重點討論dubbo的實現原理。java
SPI,Service Provider Interface,主要是被框架的開發人員使用,好比java.sql.Driver接口,其餘不一樣廠商能夠針對同一接口作出不一樣的實現,mysql和postgresql都有不一樣的實現提供給用戶,而Java的SPI機制能夠爲某個接口尋找服務實現。mysql
當服務的提供者提供了一種接口的實現以後,須要在classpath下的META-INF/services/目錄裏建立一個以服務接口命名的文件,這個文件裏的內容就是這個接口的具體的實現類。當其餘的程序須要這個服務的時候,就能夠經過查找這個jar包(通常都是以jar包作依賴)的META-INF/services/中的配置文件,配置文件中有接口的具體實現類名,能夠根據這個類名進行加載實例化,就可使用該服務了。JDK中查找服務的實現的工具類是:java.util.ServiceLoadersql
由於本文的主體內容是dubbo,因此這邊就不對ServiceLoader的源碼進行深刻的解析。這邊寫了一個例子。express
package com.shang.spi; /** * @author shang * @date 2019/1/5 */ public interface DubboService { void sayHello(); }
DubboService的實現類AppleServiceapache
package com.shang.spi; /** * @author shang * @date 2019/1/5 */ public class AppleService implements DubboService { @Override public void sayHello() { System.out.println("apple"); } } package com.shang.spi; import java.util.Iterator; import java.util.ServiceLoader;
/** * @author shang * @date 2019/1/5 */ public class ServiceMain { public static void main(String[] args) { ServiceLoader<DubboService> spiLoader = ServiceLoader.load(DubboService.class); Iterator<DubboService> iteratorSpi = spiLoader.iterator(); while (iteratorSpi.hasNext()) { DubboService dubboService = iteratorSpi.next(); dubboService.sayHello(); } } }
dubbo的spi實現原理和java spi類似,只不過加強了一些功能和優化。java spi的是把全部的spi都加載到內存,但對於dubbo來講可能只須要加載用戶指定的實現方式,而不須要所有加載進來,所有加載也會有性能問題,因此dubbo實現的是在有用到的時候去加載這些擴展組件。緩存
一、@SPI註解,被此註解標記的接口,就表示是一個可擴展的接口,並標註默認值。
二、@Adaptive註解,有兩種註解方式:一種是註解在類上,一種是註解在方法上。
三、@Activate註解,此註解須要註解在類上或者方法上,並註明被激活的條件,以及全部的被激活實現類中的排序信息app
本文重點分析1和2的解析過程,3實際上是在loadFile的時候可能被激活。框架
public class ReferenceConfig<T> extends AbstractReferenceConfig { private static final long serialVersionUID = -5864351140409987595L; private static final Protocol refprotocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension(); private static final Cluster cluster = ExtensionLoader.getExtensionLoader(Cluster.class).getAdaptiveExtension(); private static final ProxyFactory proxyFactory = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); ... }
咱們來看下消費者生成refer的代碼。從ReferenceConfig這個類中咱們能夠看到須要初始化的擴展類有Protocol、Cluster和ProxyFactory。那麼其實就是須要的時候再去加載。全部的實現都在ExtensionLoader類中。這個類也不負責,一千行左右的代碼。
下面咱們就跟着Protocol的擴展來看下源碼的實現方式。less
Protocol refprotocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension();
在看實現的代碼以前咱們先看加Protocol這個擴展類,爲了儘可能的簡潔刪除了一些包路徑和註釋。
能夠看到Protocol的spi的默認值是dubbo,這個在初始化類的時候頗有用,假如你的Protocol實現類有不少,在dubbo中就有:ide
@SPI("dubbo") public interface Protocol { int getDefaultPort(); @Adaptive <T> Exporter<T> export(Invoker<T> invoker) throws RpcException; @Adaptive <T> Invoker<T> refer(Class<T> type, URL url) throws RpcException; void destroy(); default void destroyServer() { //空實現 } }
那麼spi的Adaptive就是一種自適應的註解,具體是怎麼實現的咱們繼續看代碼。
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!"); } if(!withExtensionAnnotation(type)) { throw new IllegalArgumentException("Extension type(" + type + ") is not extension, because WITHOUT @" + SPI.class.getSimpleName() + " Annotation!"); } ExtensionLoader<T> loader = (ExtensionLoader<T>) EXTENSION_LOADERS.get(type); if (loader == null) { EXTENSION_LOADERS.putIfAbsent(type, new ExtensionLoader<T>(type)); loader = (ExtensionLoader<T>) EXTENSION_LOADERS.get(type); } return loader; }
getExtensionLoader方法最主要的實現就是把全部的擴展放到EXTENSION_LOADERS這個容器中,避免二次加載。
private static final ConcurrentMap<Class<?>, ExtensionLoader<?>> EXTENSION_LOADERS = new ConcurrentHashMap<Class<?>, ExtensionLoader<?>>();
下面其實就是爲了獲取自適應的擴展機制,Adaptive這個註解的自適應。調用的路徑大概是這樣的:
getAdaptiveExtension()--> createAdaptiveExtension()--> getAdaptiveExtensionClass()--> getExtensionClasses()--> loadExtensionClasses()
public T getAdaptiveExtension() { Object instance = cachedAdaptiveInstance.get(); if (instance == null) { if(createAdaptiveInstanceError == null) { synchronized (cachedAdaptiveInstance) { instance = cachedAdaptiveInstance.get(); if (instance == null) { try { //建立自適應擴展 instance = createAdaptiveExtension(); //設置緩存 cachedAdaptiveInstance.set(instance); } catch (Throwable t) { createAdaptiveInstanceError = t; throw new IllegalStateException("fail to create adaptive instance: " + t.toString(), t); } } } } else { throw new IllegalStateException("fail to create adaptive instance: " + createAdaptiveInstanceError.toString(), createAdaptiveInstanceError); } } return (T) instance; }
createAdaptiveExtension經過名字就能能夠知道這是建立自適應的擴展對象
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); } }
路徑:getAdaptiveExtensionClass->getExtensionClasses->loadExtensionClasses->loadFile
cachedAdaptiveClass會在loadFile進行獲取
private Class<?> getAdaptiveExtensionClass() { getExtensionClasses(); //若是緩存中已經找到自適應類的話直接返回,意思也就是這個spi有Adaptive的註解類 //好比:當前獲取的自適應實現類是AdaptiveExtensionFactory或者是AdaptiveCompiler,就直接返回,這兩個類是特殊用處的,不用代碼生成,而是現成的代碼 if (cachedAdaptiveClass != null) { return cachedAdaptiveClass; } //不然須要代理類生成相關代理 return cachedAdaptiveClass = createAdaptiveExtensionClass(); }
getExtensionClasses->loadFile直接從文件加載
private Map<String, Class<?>> getExtensionClasses() { Map<String, Class<?>> classes = cachedClasses.get(); if (classes == null) { synchronized (cachedClasses) { classes = cachedClasses.get(); if (classes == null) { classes = loadExtensionClasses(); cachedClasses.set(classes); } } } return classes; } // 此方法已經getExtensionClasses方法同步過。 private Map<String, Class<?>> loadExtensionClasses() { final SPI defaultAnnotation = type.getAnnotation(SPI.class); if(defaultAnnotation != null) { String value = defaultAnnotation.value(); if(value != null && (value = value.trim()).length() > 0) { String[] names = NAME_SEPARATOR.split(value); if(names.length > 1) { throw new IllegalStateException("more than 1 default extension name on extension " + type.getName() + ": " + Arrays.toString(names)); } if(names.length == 1) cachedDefaultName = names[0]; } } Map<String, Class<?>> extensionClasses = new HashMap<String, Class<?>>(); //從文件加載 loadFile(extensionClasses, DUBBO_INTERNAL_DIRECTORY); loadFile(extensionClasses, DUBBO_DIRECTORY); loadFile(extensionClasses, SERVICES_DIRECTORY); return extensionClasses; }
private void loadFile(Map<String, Class<?>> extensionClasses, String dir) { String fileName = dir + type.getName(); try { Enumeration<java.net.URL> urls; ClassLoader classLoader = findClassLoader(); if (classLoader != null) { urls = classLoader.getResources(fileName); } else { urls = ClassLoader.getSystemResources(fileName); } if (urls != null) { while (urls.hasMoreElements()) { //配置文件路徑 java.net.URL url = urls.nextElement(); try { BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "utf-8")); try { String line = null; //每次處理一行 while ((line = reader.readLine()) != null) { //#號之後的爲註釋 final int ci = line.indexOf('#'); //註釋去掉 if (ci >= 0) line = line.substring(0, ci); line = line.trim(); if (line.length() > 0) { try { String name = null; //=號以前的爲擴展名字,後面的爲擴展類實現的全限定名 int i = line.indexOf('='); if (i > 0) { name = line.substring(0, i).trim(); line = line.substring(i + 1).trim(); } if (line.length() > 0) { //加載擴展類的實現 Class<?> clazz = Class.forName(line, true, classLoader); //查看類型是否匹配 //type是Protocol接口 //clazz就是Protocol的各個實現類 if (! type.isAssignableFrom(clazz)) { throw new IllegalStateException(); } //若是實現類是@Adaptive類型的,會賦值給cachedAdaptiveClass,這個用來存放被@Adaptive註解的實現類 if (clazz.isAnnotationPresent(Adaptive.class)) { if(cachedAdaptiveClass == null) { cachedAdaptiveClass = clazz; } else if (! cachedAdaptiveClass.equals(clazz)) { throw new IllegalStateException(); } } else {//不是@Adaptice類型的類,就是沒有註解@Adaptive的實現類 try {//判斷是不是wrapper類型 //若是獲得的實現類的構造方法中的參數是擴展點類型的,就是一個Wrapper類 //好比ProtocolFilterWrapper,實現了Protocol類, //而它的構造方法是這樣public ProtocolFilterWrapper(Protocol protocol) //就說明這個類是一個包裝類 clazz.getConstructor(type); //cachedWrapperClasses用來存放當前擴展點實現類中的包裝類 Set<Class<?>> wrappers = cachedWrapperClasses; if (wrappers == null) { cachedWrapperClasses = new ConcurrentHashSet<Class<?>>(); wrappers = cachedWrapperClasses; } wrappers.add(clazz); } catch (NoSuchMethodException e) { //沒有上面提到的構造器,則說明不是wrapper類型 //獲取無參構造 clazz.getConstructor(); //沒有名字,就是配置文件中沒有xxx=xxxx.com.xxx這種 if (name == null || name.length() == 0) { //去找@Extension註解中配置的值 name = findAnnotationName(clazz); //若是還沒找到名字,從類名中獲取 if (name == null || name.length() == 0) { //好比clazz是DubboProtocol,type是Protocol //這裏獲得的name就是dubbo if (clazz.getSimpleName().length() > type.getSimpleName().length() && clazz.getSimpleName().endsWith(type.getSimpleName())) { name = clazz.getSimpleName().substring(0, clazz.getSimpleName().length() - type.getSimpleName().length()).toLowerCase(); } else { throw new IllegalStateException("No such extension name for the class " + clazz.getName() + " in the config " + url); } } } //有可能配置了多個名字 String[] names = NAME_SEPARATOR.split(name); if (names != null && names.length > 0) { //是不是Active類型的類 Activate activate = clazz.getAnnotation(Activate.class); if (activate != null) { //第一個名字做爲鍵,放進cachedActivates這個map中緩存 cachedActivates.put(names[0], activate); } for (String n : names) { if (! cachedNames.containsKey(clazz)) { //放入Extension實現類與名稱映射的緩存中去,每一個class只對應第一個名稱有效 cachedNames.put(clazz, n); } Class<?> c = extensionClasses.get(n); if (c == null) { //放入到extensionClasses緩存中去,多個name可能對應一份extensionClasses extensionClasses.put(n, clazz); } else if (c != clazz) { throw new IllegalStateException("Duplicate extension " + type.getName() + " name " + n + " on " + c.getName() + " and " + clazz.getName()); } } } } } } } catch (Throwable t) { } } } // end of while read lines } finally { reader.close(); } } catch (Throwable t) { } } // end of while urls } } catch (Throwable t) { } }
好了,仍是要回到getAdaptiveExtensionClass這個方法,上面的loadFile是按規則加載了全部的type類型的spi類,那麼若是生成自適應類呢?
咱們繼續看createAdaptiveExtensionClass這個方法的createAdaptiveExtensionClassCode
private Class<?> createAdaptiveExtensionClass() { String code = createAdaptiveExtensionClassCode(); ClassLoader classLoader = findClassLoader(); com.alibaba.dubbo.common.compiler.Compiler compiler = ExtensionLoader.getExtensionLoader(com.alibaba.dubbo.common.compiler.Compiler.class).getAdaptiveExtension(); return compiler.compile(code, classLoader); }
createAdaptiveExtensionClassCode的代碼有點長,具體就是生成代理類,咱們先看下代碼:
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!"); 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); 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); } 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; } } String defaultExtName = cachedDefaultName; String getNameCode = null; for (int i = value.length - 1; i >= 0; --i) { if(i == value.length - 1) { if(null != defaultExtName) { 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], defaultExtName); else getNameCode = String.format("( url.getProtocol() == null ? \"%s\" : url.getProtocol() )", defaultExtName); } 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\")", 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(); }
那麼他生成的代理類是怎麼樣的呢?咱們仍是以com.alibaba.dubbo.rpc.Protocol 爲例,他生成的代理類就是Protocol$Adpative,中間多了一個$。
import com.alibaba.dubbo.common.extension.ExtensionLoader; public class Protocol$Adpative implements com.alibaba.dubbo.rpc.Protocol { public com.alibaba.dubbo.rpc.Invoker refer(java.lang.Class arg0, com.alibaba.dubbo.common.URL arg1) throws java.lang.Class { if (arg1 == null) throw new IllegalArgumentException("url == null"); com.alibaba.dubbo.common.URL url = arg1; 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(arg0, arg1); } public com.alibaba.dubbo.rpc.Exporter export(com.alibaba.dubbo.rpc.Invoker arg0) throws com.alibaba.dubbo.rpc.Invoker { if (arg0 == null) throw new IllegalArgumentException("com.alibaba.dubbo.rpc.Invoker argument == null"); if (arg0.getUrl() == null) throw new IllegalArgumentException("com.alibaba.dubbo.rpc.Invoker argument getUrl() == null");com.alibaba.dubbo.common.URL url = arg0.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(arg0); } 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!"); } 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!"); } }
其餘的類型的代理代碼生成是相似的,上面的代碼是硬編碼,須要把他編譯並加載到內存中,具體仍是要回到createAdaptiveExtensionClass這個方法,代碼在上面,這裏就再也不貼了,須要經過Compiler這個類找到對應的自適應實現,這裏獲得的就是AdaptiveCompiler,最後調用compiler.compile(code, classLoader);來編譯上面生成的類並返回,先進入AdaptiveCompiler的compile方法:
public Class<?> compile(String code, ClassLoader classLoader) { Compiler compiler; ExtensionLoader<Compiler> loader = ExtensionLoader.getExtensionLoader(Compiler.class); //默認的Compiler名字 String name = DEFAULT_COMPILER; // copy reference //有指定了Compiler名字,就使用指定的名字來找到Compiler實現類 if (name != null && name.length() > 0) { compiler = loader.getExtension(name); } else {//沒有指定Compiler名字,就查找默認的Compiler的實現類 compiler = loader.getDefaultExtension(); } return compiler.compile(code, classLoader); }
/* * Copyright 1999-2011 Alibaba Group. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.dubbo.common.compiler; import com.alibaba.dubbo.common.extension.SPI; /** * Compiler. (SPI, Singleton, ThreadSafe) * * @author william.liangf */ @SPI("javassist") public interface Compiler { /** * Compile java source code. * * @param code Java source code * @param classLoader TODO * @return Compiled class */ Class<?> compile(String code, ClassLoader classLoader); }
至此整個自適應的代理方式都已經解析完了。可是我以爲實現的有點過於複雜了,是適應類的存在是頗有必要的嗎?我以爲也未必。 感受在spi的實現中插入了Adaptive等的實現是把簡單的spi機制搞得複雜化了,繞了一大圈去解決一個自適應代理類等方式是否能夠簡單化。