Java SPI(Service Provider Interface)
(1)接口java
public interface SPIService { public void printService(); }
(2)接口實現1apache
public class SPIServiceImpl implements SPIService { public void printService() { System.out.println("Hello World"); } }
(3)接口實現2數組
public class SPIServiceImpl2 implements SPIService { public void printService() { System.out.println("Hello World2"); } }
(4)接口實現2緩存
public class SPIServiceImpl3 implements SPIService { public void printService() { System.out.println("Hello World3"); } }
(5)在resource目錄下創建META-INF/services目錄,創建接口的全路徑名文件(這裏是gdut.ff.spi.SPIService),在文件裏以分行符分隔接口實現類的全路徑名。
app
(6)Main方法ide
import java.util.ServiceLoader; public class SPIServiceMain { public static void main(String[] args) { ServiceLoader<SPIService> serviceLoader = ServiceLoader.load(SPIService.class); for (SPIService spiService:serviceLoader) { spiService.printService(); } } }
java.util.ServiceLoader能夠獲取接口的所有實現,具體調用哪一個實現是用戶在META-INF/services中配置。url
Dubbo SPI
(1)在接口上添加註解@SPIspa
import org.apache.dubbo.common.extension.SPI; @SPI("spiServiceImpl") public interface SPIService { public void printService(); }
(2)在META-INF/dubbo/internal文件夾下創建全路徑名配置文件,內容以下.net
spiServiceImpl=gdut.ff.spi.SPIServiceImpl
(3)Main方法:經過ExtensionLoader獲取接口SPIService.class的默認實現code
public class SPIServiceMain { public static void main(String[] args) { SPIService defaultExtension = ExtensionLoader.getExtensionLoader(SPIService.class).getDefaultExtension(); defaultExtension.printService(); } }
Java SPI 和 Dubbo SPI 對比
(1) Java SPI會一次性實例化全部拓展點的實現,而Dubbo SPI並不會當即所有初始化。
(2) Dubbo SPI實現了IoC和AOP機制。
(3) Dubbo SPI兼容Java SPI的配置方式和配置內容,在Dubbo啓動的時候,會掃描META-INF/services/,META-INF/dubbo/,META-INF/dubbo/internal/三個目錄
拓展點註解 @SPI
(1)@SPI可使用在類、接口和枚舉類上。
(2)標誌這是Dubbo SPI接口。
(3)SPI註解有一個value屬性,能夠經過這個屬性設置這個接口的默認實現類。
@Documented @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE}) public @interface SPI { /** * 默認實現類名稱 */ String value() default ""; }
拓展點自適應註解 @Adaptive
(1)@Adaptive註解能夠標記在類、接口、枚舉和方法上。
(2)使用@Adaptive註解,能夠動態地經過URL中的參數來肯定具體使用的實現類,從而解決了自動加載中的實例注入問題。
(3)當傳遞的參數URL沒有參數key能夠匹配@Adaptive的value數組的某一個值,就會使用@SPI("XXX")默認實現。
(4)當傳遞的參數URL有參數key能夠匹配@Adaptive的value數組的某一個值(順序是key依次匹配),就使用該key對應的value值。查找該value值在配置文件(META-INF/dubbo/internal/目錄下)對應的實現類。
(5)當在某個實現類上加了@Adaptive註解,優先級最高,不管默認實現@SPI的值是什麼和URL傳遞了什麼參數,都會直接調用帶有@Adaptive註解的類。
(6)方法級別註解會生成和編譯動態實現類,而類級別的註解不會生成動態類。
(7)會緩存兩個與@Adaptive有關的對象,Adaptive具體實現類的Class類型緩存在cachedAdaptiveClass中;Class的具體實例化對象緩存在cachedAdaptiveInstance中。
@SPI("spiServiceImpl") public interface SPIService { @Adaptive({"test"}) public void printService(URL url); }
spiServiceImpl=gdut.ff.spi.SPIServiceImpl spiServiceImpl2=gdut.ff.spi.SPIServiceImpl2 spiServiceImpl3=gdut.ff.spi.SPIServiceImpl3
public class SPIServiceMain { public static void main(String[] args) { SPIService defaultExtension = ExtensionLoader.getExtensionLoader(SPIService.class).getAdaptiveExtension(); //這裏設置@Adaptive的參數test的值是spiServiceImpl2,表示調用gdut.ff.spi.SPIServiceImpl2 URL url = URL.valueOf("file://localhost/hello?test=spiServiceImpl2"); defaultExtension.printService(url); } } 輸出是:Hello World2
(8)若是在多個實現類上面都加了@Adaptive註解,會拋出「發現多於一個Adaptive類」錯誤。
拓展點自適應激活註解 @Activate
(1)能夠標記在類、枚舉、接口和方法上。主要使用在有多個拓展點,須要根據不一樣的應用場景激活。
ExtensionLoader工做原理
public class SPIServiceMain { public static void main(String[] args) { URL url = URL.valueOf("file://localhost/hello"); SPIService defaultService = ExtensionLoader.getExtensionLoader(SPIService.class).getExtension("true"); defaultService.printService(url); } }
(1)getExtension
private final ConcurrentMap<String, Holder<Object>> cachedInstances = new ConcurrentHashMap<String, Holder<Object>>(); public T getExtension(String name) { if (name == null || name.length() == 0) throw new IllegalArgumentException("Extension name == null"); if ("true".equals(name)) { //加載返回默認拓展類 return getDefaultExtension(); } //先在緩存實例中獲取 Holder<Object> holder = cachedInstances.get(name); if (holder == null) { cachedInstances.putIfAbsent(name, new Holder<Object>()); holder = cachedInstances.get(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; }
private T createExtension(String name) { 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 (wrapperClasses != null && !wrapperClasses.isEmpty()) { for (Class<?> wrapperClass : wrapperClasses) { instance = injectExtension((T) wrapperClass.getConstructor(type).newInstance(instance)); } } return instance; } catch (Throwable t) { throw new IllegalStateException("Extension instance(name: " + name + ", class: " + type + ") could not be instantiated: " + t.getMessage(), t); } }
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; }
private Map<String, Class<?>> loadExtensionClasses() { //獲取接口上的註解SPI final SPI defaultAnnotation = type.getAnnotation(SPI.class); if (defaultAnnotation != null) { //@SPI註解的value值 String value = defaultAnnotation.value(); if ((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<?>>(); // META-INF/dubbo/internal/接口全路徑名 loadDirectory(extensionClasses, DUBBO_INTERNAL_DIRECTORY, type.getName()); // META-INF/dubbo/internal/接口全路徑名 loadDirectory(extensionClasses, DUBBO_INTERNAL_DIRECTORY, type.getName().replace("org.apache", "com.alibaba")); // META-INF/dubbo/接口全路徑名 loadDirectory(extensionClasses, DUBBO_DIRECTORY, type.getName()); // META-INF/dubbo/接口全路徑名 loadDirectory(extensionClasses, DUBBO_DIRECTORY, type.getName().replace("org.apache", "com.alibaba")); // META-INF/services/接口全路徑名 loadDirectory(extensionClasses, SERVICES_DIRECTORY, type.getName()); // META-INF/services/接口全路徑名 loadDirectory(extensionClasses, SERVICES_DIRECTORY, type.getName().replace("org.apache", "com.alibaba")); return extensionClasses; }
private void loadDirectory(Map<String, Class<?>> extensionClasses, String dir, String type) { String fileName = dir + type; 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 resourceURL = urls.nextElement(); loadResource(extensionClasses, classLoader, resourceURL); } } } catch (Throwable t) { logger.error("Exception when load extension class(interface: " + type + ", description file: " + fileName + ").", t); } }
private void loadResource(Map<String, Class<?>> extensionClasses, ClassLoader classLoader, java.net.URL resourceURL) { try { //IO流讀取META-INF文件夾的配置文件 BufferedReader reader = new BufferedReader(new InputStreamReader(resourceURL.openStream(), "utf-8")); try { String line; 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) { loadClass(extensionClasses, resourceURL, Class.forName(line, true, classLoader), name); } } catch (Throwable t) { IllegalStateException e = new IllegalStateException("Failed to load extension class(interface: " + type + ", class line: " + line + ") in " + resourceURL + ", cause: " + t.getMessage(), t); exceptions.put(line, e); } } } } finally { reader.close(); } } catch (Throwable t) { logger.error("Exception when load extension class(interface: " + type + ", class file: " + resourceURL + ") in " + resourceURL, t); } }
private void loadClass(Map<String, Class<?>> extensionClasses, java.net.URL resourceURL, Class<?> clazz, String name) throws NoSuchMethodException { //判斷clazz是不是type的子類 if (!type.isAssignableFrom(clazz)) { throw new IllegalStateException("Error when load extension class(interface: " + type + ", class line: " + clazz.getName() + "), class " + clazz.getName() + "is not subtype of interface."); } //判斷實現類clazz是否有@Adaptive註解 if (clazz.isAnnotationPresent(Adaptive.class)) { if (cachedAdaptiveClass == null) { cachedAdaptiveClass = clazz; } else if (!cachedAdaptiveClass.equals(clazz)) { throw new IllegalStateException("More than 1 adaptive class found: " + cachedAdaptiveClass.getClass().getName() + ", " + clazz.getClass().getName()); } //判斷是不是包裝拓展類,若是是,緩存起來 } else if (isWrapperClass(clazz)) { Set<Class<?>> wrappers = cachedWrapperClasses; if (wrappers == null) { cachedWrapperClasses = new ConcurrentHashSet<Class<?>>(); wrappers = cachedWrapperClasses; } wrappers.add(clazz); } else { clazz.getConstructor(); if (name == null || name.length() == 0) { name = findAnnotationName(clazz); if (name.length() == 0) { throw new IllegalStateException("No such extension name for the class " + clazz.getName() + " in the config " + resourceURL); } } String[] names = NAME_SEPARATOR.split(name); if (names != null && names.length > 0) { //判斷是否有@Activate註解,若是有,緩存起來 Activate activate = clazz.getAnnotation(Activate.class); if (activate != null) { cachedActivates.put(names[0], activate); } else { // support com.alibaba.dubbo.common.extension.Activate com.alibaba.dubbo.common.extension.Activate oldActivate = clazz.getAnnotation(com.alibaba.dubbo.common.extension.Activate.class); if (oldActivate != null) { cachedActivates.put(names[0], oldActivate); } } //普通拓展類,緩存起來 for (String n : names) { if (!cachedNames.containsKey(clazz)) { cachedNames.put(clazz, n); } Class<?> c = extensionClasses.get(n); if (c == null) { extensionClasses.put(n, clazz); } else if (c != clazz) { throw new IllegalStateException("Duplicate extension " + type.getName() + " name " + n + " on " + c.getName() + " and " + clazz.getName()); } } } } }
(2)getAdaptiveExtension
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; }
private T createAdaptiveExtension() { try { return injectExtension((T) getAdaptiveExtensionClass().newInstance()); } catch (Exception e) { throw new IllegalStateException("Can not create adaptive extension " + type + ", cause: " + e.getMessage(), e); } }
private Class<?> getAdaptiveExtensionClass() { getExtensionClasses(); if (cachedAdaptiveClass != null) { return cachedAdaptiveClass; } return cachedAdaptiveClass = createAdaptiveExtensionClass(); }
ExtensionFactory
package org.apache.dubbo.common.extension; @SPI public interface ExtensionFactory { <T> T getExtension(Class<T> var1, String var2); }
有三種實現:
(1)SpiExtensionFactory
(2)SpringExtensionFactory
(3)AdaptiveExtensionFactory
代碼編譯器
(1)JDK編譯器JdkCompiler
(2)Javassist編譯器JavassistCompiler
(3)Adaptive編譯器AdaptiveCompiler
參考資料
《深刻理解Apache Dubbo與實戰》
Dubbo SPI之Adaptive詳解