JDK SPI是什麼
最近工作中聽幾個同事說了好幾次SPI這個名詞,雖然和我沒關係,但是心裏默默想還是學習一下,不然下次和我說到SPI,連是什麼都不知道那就尷尬了。
所以SPI是什麼呢?SPI全稱Service Provider Interface,在Java中還是一個比較重要的概念,是Java提供的一套用來被第三方實現或者擴展的API,或者換句話說,SPI是一種服務發現機制。
JDK SPI使用說明及示例
要使用SPI比較簡單,只需要按照以下幾個步驟操作即可:
-
在jar包的META-INF/services目錄下創建一個以"接口全限定名"爲命名的文件,內容爲實現類的全限定名
-
接口實現類所在的jar包在classpath下
-
主程序通過java.util.ServiceLoader動態狀態實現模塊,它通過掃描META-INF/services目錄下的配置文件找到實現類的全限定名,把類加載到JVM
-
SPI的實現類必須帶一個無參構造方法
接着我們看一下具體例子,首先定義一個SpiService,它是一個接口:
package org.xrq.test.spi;
public interface SpiService {
public void hello();
}
兩個實現類,分別爲SpiServiceA與SpiServiceB:
package org.xrq.test.spi;
public class SpiServiceA implements SpiService {
public void hello() {
System.out.println("SpiServiceA.Hello");
}
}
package org.xrq.test.spi;
public class SpiServiceB implements SpiService {
@Override
public void hello() {
System.out.println("SpiServiceB.hello");
}
}
接着我們建一個META-INF/services的文件夾,裏面建一個file,file的名字是接口的全限定名org.xrq.test.spi.SpiService:
文件的內容是SpiService實現類SpiServiceA、SpiServiceB的全限定名:
org.xrq.test.spi.SpiServiceA
org.xrq.test.spi.SpiServiceB
這樣就大功告成了!然後我們寫個測試類自動加載一下這兩個類:
public class SpiTest {
@Test
public void testSpi() {
ServiceLoader<SpiService> serviceLoader = ServiceLoader.load(SpiService.class);
Iterator<SpiService> iterator = serviceLoader.iterator();
while (iterator.hasNext()) {
SpiService spiService = iterator.next();
spiService.hello();
}
}
}
結果一目瞭然,調用了hello()方法:
SpiServiceA.Hello
SpiServiceB.hello
這就是SPI的使用示例,接着我們看一下SPI在實際場景中的應用。
SPI在JDBC中的應用
回看快四年前的文章《JDBC學習2:爲什麼要寫Class.forName("XXX")?》,當時技術真的是稚嫩,關於爲什麼不寫Class.forName("XXX")的解釋現在看來真的是弱爆了,根本沒有講到重點。最後一樓網友的回覆"不用寫的原因是,新版本JDBC使用了SPI"是正確答案,但當時也沒在意,這次學了一下SPI馬上就想起這個例子來了,因此就由JDBC講講SPI的實際應用。
在老版本的JDBC中,假設我們使用的是MySql,初始化JDBC的時候是需要顯式調用Class.forName("com.mysql.jdbc.Driver")這一句的,但是在某個版本之後就不需要做這一步操作了,如上所說這是通過SPI實現的,怎麼理解呢。Class.forName其實沒有實際意義,其實既不會new對象也不會反射生成對象,它只是爲了調用com.mysql.jdbc.Driver的static方法塊而已:
public class Driver extends NonRegisteringDriver implements java.sql.Driver {
//
// Register ourselves with the DriverManager
//
static {
try {
java.sql.DriverManager.registerDriver(new Driver());
} catch (SQLException E) {
throw new RuntimeException("Can't register driver!");
}
}
/**
* Construct a new driver and register it with DriverManager
*
* @throws SQLException
* if a database error occurs.
*/
public Driver() throws SQLException {
// Required for Class.forName().newInstance()
}
}
方法塊的作用只有一個,通過jdk自帶的DriverManager註冊Driver,registerDrivers方法沒什麼套路,把Driver放到CopyOnArrayList裏面而已:
public static synchronized void registerDriver(java.sql.Driver driver, DriverAction da)
throws SQLException {
/* Register the driver if it has not already been added to our list */
if(driver != null) {
registeredDrivers.addIfAbsent(new DriverInfo(driver, da));
} else {
// This is for compatibility with the original DriverManager
throw new NullPointerException();
}
println("registerDriver: " + driver);
}
從某個JDK版本,具體也不知道哪個版本,廢棄了這個操作,看下新版的DriverManager,我的是JDK1.8的:
/**
* Load the initial JDBC drivers by checking the System property
* jdbc.properties and then use the {@code ServiceLoader} mechanism
*/
static {
loadInitialDrivers();
println("JDBC DriverManager initialized");
}
直接看一下loadInitialDrivers這個方法的核心部分:
AccessController.doPrivileged(new PrivilegedAction<Void>() {
public Void run() {
ServiceLoader<Driver> loadedDrivers = ServiceLoader.load(Driver.class);
Iterator<Driver> driversIterator = loadedDrivers.iterator();
/*
* 節約篇幅,註釋省略
*/
try{
while(driversIterator.hasNext()) {
driversIterator.next();
}
} catch(Throwable t) {
// Do nothing
}
return null;
}
});
看到使用SPI的方式從META-INF/services下去找java.sql.Driver這個文件,並找到裏面的Driver實現類逐一注入。最後我們看一下Iterator的next()方法做了什麼就完全懂了,通過next()方法調用了:
private S nextService() {
if (!hasNextService())
throw new NoSuchElementException();
String cn = nextName;
nextName = null;
Class<?> c = null;
try {
c = Class.forName(cn, false, loader);
} catch (ClassNotFoundException x) {
fail(service,
"Provider " + cn + " not found");
}
if (!service.isAssignableFrom(c)) {
fail(service,
"Provider " + cn + " not a subtype");
}
try {
S p = service.cast(c.newInstance());
providers.put(cn, p);
return p;
} catch (Throwable x) {
fail(service,
"Provider " + cn + " could not be instantiated",
x);
}
throw new Error(); // This cannot happen
}
看到Class.forName了吧,雖然都是Class.forName,但是通過SPI的方式把用戶手動做的動作變成框架做。
對SPI的理解
最後談一談我對SPI的理解,學習了怎麼用SPI、SPI在實際應用中的示例之後,深刻理解SPI機制才能在以後工作中真正將SPI爲我所用。
首先大家可以注意到,標題是JDK SPI,也就是說SPI並不是JDK專屬的。是的,我理解的SPI其實是一種可插拔技術的總稱,最簡單的例子就是USB,廠商提供了USB的標準,廠家根據USB的標準制造自己的外設,例如鼠標、鍵盤、遊戲手柄等等,但是USB標準具體在電腦中是怎麼用的,廠家就不需要管了。
回到我們的代碼中也是一樣的道理。當我們開發一個框架的時候,除了保證基本的功能外,最重要的一個點是什麼?我認爲最重要的應該是松耦合,即對擴展開放、對修改關閉,保證框架實現對於使用者來說是黑盒。
框架不可能做好所有的事情,只能把共性的部分抽離出來進行流程化,松耦合實現的核心就是定義好足夠鬆散的接口,或者可以理解是擴展點,具體的擴展點讓使用者去實現,這樣不同的擴展就不需要修改源代碼或者對框架進行定製,這就是面向接口編程的好處。
回到我們框架的部分來說:
-
JDK對於SPI的實現是通過META-INF/services這個目錄 + ServiceLoader
-
Spring實現SPI的方式是留了N多的接口,例如BeanPostProcessor、InitializingBean、DisposableBean,我們只需要實現這些接口然後注入即可
對已有框架而言,我們可以通過框架給我們提供的擴展點擴展框架功能。對自己寫框架而言,記得SPI這個事情,留好足夠的擴展點,這將大大加強你寫的框架的擴展性。