最近學習了JDK SPI


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中的應用

回看快四年前的文章https://www.cnblogs.com/xrq730/p/4851944.html,這篇名為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這個事情,留好足夠的擴展點,這將大大加強你寫的框架的擴展性。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM