Java中的SPI機(jī)制

在學(xué)習(xí)SPI之前,在了解一下API(應(yīng)用程序接口),API就是服務(wù)方定義好接口和實(shí)現(xiàn),然后提供暴露一個(gè)接口給調(diào)用方。那什么是SPI呢?

SPI介紹

SPI ,全稱為 Service Provider Interface,是一種服務(wù)發(fā)現(xiàn)機(jī)制。它通過(guò)在classpath路徑下的META-INF/services文件夾查找文件,自動(dòng)加載文件里所定義的類。Java自身提供的服務(wù)發(fā)現(xiàn)機(jī)制,是掃描META-INF/services文件夾文件定義的類。但是,也可以自己實(shí)現(xiàn)SPI功能,掃描不同的文件夾文件,像DubboSPI機(jī)制和SpirngBootSPI機(jī)制,都是自己實(shí)現(xiàn)的SPI功能,這為很多框架拓展功能提供了更多的可能性。

SPI可以讓開發(fā)者拓展JDK自身或者框架本身的功能,就是說(shuō)開發(fā)者是服務(wù)實(shí)現(xiàn)方,而JDK或者框架是服務(wù)調(diào)用方。

簡(jiǎn)而言之,就是指定那個(gè)目錄下,通過(guò)全限定類名去加載對(duì)應(yīng)的類。

思考,為什么需要SPI

思考一個(gè)問(wèn)題,有這樣一個(gè)需求,需要為某個(gè)開源框架或者已有的系統(tǒng)拓展一下功能。

比較常見的做法可能是在原來(lái)的代碼進(jìn)行修改,然后重新編譯打包再發(fā)布。

那有沒有方法可以不修改原來(lái)代碼就可以進(jìn)行拓展呢?答案就是SPI,這要求原來(lái)提供框架的開發(fā)者,使用SPI,定義接口(interface)或者抽象類(abstract class), 以及實(shí)現(xiàn)了服務(wù)接口的具體類。

在使用中,框架提供接口,框架提供基礎(chǔ)的實(shí)現(xiàn)類,開發(fā)者可以去拓展自己的實(shí)現(xiàn)類。其中實(shí)現(xiàn)類的定義需要放在META-INF/services下面, 在運(yùn)行時(shí)框架會(huì)掃描服務(wù)配置文件下面的實(shí)現(xiàn)類,從而框架就可以調(diào)用。

使用實(shí)例

定義一個(gè)接口

public interface SPIService {
    void service();
}

原系統(tǒng)調(diào)用

public class SPIServiceTest {
    public static void main(String[] args) {
        ServiceLoader<SPIService> spiServices = ServiceLoader.load(SPIService.class);
        Iterator<SPIService> iterator = spiServices.iterator();
        while (iterator.hasNext()) {
            SPIService next = iterator.next();
            next.service();
        }
    }
}

實(shí)現(xiàn)類1

public class SPIServiceA implements SPIService {
    @Override
    public void service() {
        System.out.println("SPIServiceA");
    }
}

實(shí)現(xiàn)類2

public class SPIServiceB implements SPIService {
    @Override
    public void service() {
        System.out.println("SPIServiceB");
    }
}

resource下面新建META-INF/services目錄,然后新建文件com.spi.learn.service.SPIService

文件內(nèi)容

com.spi.learn.service.SPIServiceA
com.spi.learn.service.SPIServiceB

JDK應(yīng)用場(chǎng)景——Driver

java.sql.DriverManager類的loadInitialDrivers()方法中

    private static void loadInitialDrivers() {
        ....

        AccessController.doPrivileged(new PrivilegedAction<Void>() {
            public Void run() {

                ServiceLoader<Driver> loadedDrivers = ServiceLoader.load(Driver.class);
                Iterator<Driver> driversIterator = loadedDrivers.iterator();

                /* Load these drivers, so that they can be instantiated.
                 * It may be the case that the driver class may not be there
                 * i.e. there may be a packaged driver with the service class
                 * as implementation of java.sql.Driver but the actual class
                 * may be missing. In that case a java.util.ServiceConfigurationError
                 * will be thrown at runtime by the VM trying to locate
                 * and load the service.
                 *
                 * Adding a try catch block to catch those runtime errors
                 * if driver not available in classpath but it's
                 * packaged as service and that service is there in classpath.
                 */
                try{
                    while(driversIterator.hasNext()) {
                        driversIterator.next();
                    }
                } catch(Throwable t) {
                // Do nothing
                }
                return null;
            }
        });

        ....
    }

其中ServiceLoader.load(Driver.class)會(huì)去加載META-INF/services目錄下,所有實(shí)現(xiàn)了Driver接口的類,因此在mysql中實(shí)現(xiàn)了Driver接口的類會(huì)被加載,然后執(zhí)行靜態(tài)塊,這樣子就實(shí)現(xiàn)了不同數(shù)據(jù)庫(kù)的驅(qū)動(dòng)注冊(cè)。

com.mysql.jdbc.Driver

public class Driver extends NonRegisteringDriver implements java.sql.Driver {
    //
    // Register ourselves with the DriverManager
    // static塊,執(zhí)行這行Class.forName("com.mysql.jdbc.Driver");的時(shí)候,會(huì)調(diào)用static塊
    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()
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容