SPI 外部接口實(shí)現(xiàn)類

上篇文章AJ-Captcha用戶行為驗(yàn)證碼中提到SPI,查看了相應(yīng)的源碼實(shí)現(xiàn),覺(jué)得挺新奇的;就單獨(dú)拎出來(lái)講解一下,加深印象。

1、什么是SPI?

??SPI全稱Service Provider Interface,是Java提供的一套用來(lái)被第三方實(shí)現(xiàn)或者擴(kuò)展的接口,它可以用來(lái)啟用框架擴(kuò)展和替換組件。
SPI的作用就是為這些被擴(kuò)展的API尋找服務(wù)實(shí)現(xiàn)。

??我的理解:在引用第三方j(luò)ar時(shí),提供自己外部實(shí)現(xiàn)接口類。

2、使用場(chǎng)景

??內(nèi)部jar接口外部實(shí)現(xiàn)拓展場(chǎng)景

3、簡(jiǎn)單實(shí)現(xiàn)

  • META-INF.services下創(chuàng)建接口完整名稱文件

  • 內(nèi)部?jī)?nèi)容為實(shí)現(xiàn)類路徑

com.anji.captcha.demo.service.CaptchaCacheServiceRedisImpl
  • jar包內(nèi)部實(shí)現(xiàn)({@link com.anji.captcha.service.impl.CaptchaServiceFactory}),通過(guò)ServiceLoader.load(CaptchaCacheService.class)將接口實(shí)現(xiàn)類保存在Map<Type, CaptchaService>集合中
public static CaptchaCacheService getCache(String cacheType) {
    return cacheService.get(cacheType);
}

public volatile static Map<String, CaptchaService> instances = new HashMap();
public volatile static Map<String, CaptchaCacheService> cacheService = new HashMap();

static {
    ServiceLoader<CaptchaCacheService> cacheServices = ServiceLoader.load(CaptchaCacheService.class);
    for (CaptchaCacheService item : cacheServices) {
        cacheService.put(item.type(), item);
    }
    logger.info("supported-captchaCache-service:{}", cacheService.keySet().toString());
    ServiceLoader<CaptchaService> services = ServiceLoader.load(CaptchaService.class);
    for (CaptchaService item : services) {
        instances.put(item.captchaType(), item);
    }
    ;
    logger.info("supported-captchaTypes-service:{}", instances.keySet().toString());
}

4、原理解析

ServiceLoader
?著作權(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)容