上篇文章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
