SPI 機制,全稱為 Service Provider Interface,是一種服務發現機制,它通過在 ClassPath 路徑下的 META-INF/services 檔案夾查找檔案,自動加載檔案里所定義的類,這一機制為很多框架擴展提供了可能,比如在 Dubbo、JDBC 中都使用到了 SPI 機制,本文介紹了 Java SPI 機制以及在模塊化和非模塊話專案中的實作方式(此處的模塊化指 Java9 引入的模塊化)
SPI 機制介紹
SPI 全稱 Service Provider Interface,是 Java 提供的一套用來被第三方實作或者擴展的介面,它可以用來啟用框架擴展和替換組件, SPI 的作用就是為這些被擴展的 API 尋找服務實作,
SPI 和 API 的區別
API (Application Programming Interface)在大多數情況下,都是實作方制定介面并完成對介面的實作,呼叫方僅僅依賴介面呼叫,且無權選擇不同實作, 從使用人員上來說,API 直接被應用開發人員使用,如下圖所示,其中模塊 A 為介面制定方和實作方,而模塊 B 為介面的使用放,

維基百科關于 API 的描述:In building applications, an API (application programming interface) simplifies programming by abstracting the underlying implementation and only exposing objects or actions the developer needs. While a graphical interface for an email client might provide a user with a button that performs all the steps for fetching and highlighting new emails, an API for file input/output might give the developer a function that copies a file from one location to another without requiring that the developer understand the file system operations occurring behind the scenes.
SPI (Service Provider Interface)是呼叫方來制定介面規范,提供給外部來實作,呼叫方在呼叫時則選擇自己需要的外部實作,可用于啟用框架擴展和可替換組件, 從使用人員上來說,SPI 被框架擴展人員使用,如下圖所示,A 模塊是介面的定義方和使用方,而 B 模塊則是介面實作方,

SPI 維基百科定義:Service Provider Interface (SPI) is an API intended to be implemented or extended by a third party. It can be used to enable framework extension and replaceable components
SPI java 官方定義:A service is a well-known set of interfaces and (usually abstract) classes. A service provider(SPI) is a specific implementation of a service. The classes in a provider typically implement the interfaces and subclass the classes defined in the service itself. Service providers can be installed in an implementation of the Java platform in the form of extensions, that is, jar files placed into any of the usual extension directories. Providers can also be made available by adding them to the application's class path or by some other platform-specific means.
SPI 的優點
使用 Java SPI 機制的優勢是實作解耦,使得介面的定義與具體業務實作分離,而不是耦合在一起,應用行程可以根據實際業務情況啟用或替換具體組件,以 java 中的 JDBC 資料庫驅動為例,java 官方在核心庫制定了 java.sql.Driver 資料庫驅動介面,使用該介面實作了資料庫鏈接等邏輯,但是并沒有具體實作資料庫驅動介面,而是交給 MySql 等廠商去實作具體的資料庫介面,
參考自博客:Java SPI 主要是應用于廠商自定義組件或插件中,在 java.util.ServiceLoader 的檔案里有比較詳細的介紹,簡單的總結下 java SPI 機制的思想:我們系統里抽象的各個模塊,往往有很多不同的實作方案,比如日志模塊、xml 決議模塊、jdbc 模塊等方案,面向的物件的設計里,我們一般推薦模塊之間基于介面編程,模塊之間不對實作類進行硬編碼,一旦代碼里涉及具體的實作類,就違反了可拔插的原則,如果需要替換一種實作,就需要修改代碼,為了實作在模塊裝配的時候能不在程式里動態指明,這就需要一種服務發現機制, Java SPI 就是提供這樣的一個機制:為某個介面尋找服務實作的機制,有點類似 IOC 的思想,就是將裝配的控制權移到程式之外,在模塊化設計中這個機制尤其重要,
SPI 的約定
服務提供方需要通過一些約定告訴系統自己所提供的服務的位置,java9 之后一共有兩種約定方式:
- 通過在 META-INF/services/ 目錄下配置相關檔案實作,
- 通過 java9 jigsaw 的匯出陳述句指定服務位置,
A service provider is a single type, usually a concrete class. An interface or abstract class is permitted because it may declare a static provider method, discussed later. The type must be public and must not be an inner class.
A service provider and its supporting code may be developed in a module, which is then deployed on the application module path or in a modular image. Alternatively, a service provider and its supporting code may be packaged as a JAR file and deployed on the application class path. The advantage of developing a service provider in a module is that the provider can be fully encapsulated to hide all details of its implementation.
An application that obtains a service loader for a given service is indifferent to whether providers of the service are deployed in modules or packaged as JAR files. The application instantiates service providers via the service loader's iterator, or via Provider objects in the service loader's stream, without knowledge of the service providers' locations.
模塊化陳述句約定
模塊化陳述句約定適用于專案已經模塊化的情況,以 java.sql.Driver 為例,在模塊化檔案 module-info.java 中添加如下陳述句,就可以向應用提供指定的服務:
provides java.sql.Driver with com.wangzemin.learning.provider.TestDriverProvider;
下文以一個自定義的 java.sql.Driver 服務提供者(也可以自己隨意再另外一個模塊定義一個介面)為例,展示 SPI 在 java 模塊化情況下約定的使用方式,
1. 示例專案目錄結構:
本文提供了一個完整的例子用于測驗主要包含三個檔案,TestDriverProvider(自定義的 Driver 服務提供者),module-info.java(java 模塊化檔案),Main(用于除錯以及輸出結果)

2. 示例檔案內容
TestDriverProvider.java
public class TestDriverProvider implements Driver {
// Override 的方法都為空,
}
模塊化檔案 module-info.java:
module provider {
uses java.sql.Driver;
requires java.sql;
// 指定自定義的TestDriverProvider為Driver服務的提供者
provides java.sql.Driver with com.wangzemin.learning.provider.TestDriverProvider;
}
主函式(ServiceLoader 用于查找合適的服務提供者,下文會詳細介紹):
public class Main {
public static void main(String[] args) {
ServiceLoader<Driver> loader = ServiceLoader.load(Driver.class);
for (Driver item : loader) {
System.out.println("Get class:" + item.getClass().descriptorString());
}
}
}
3. 示例的輸出
Get class:Lcom/wangzemin/learning/provider/TestDriverProvider;
由輸出可以看到,ServiceLoader 可以成功定位到 TestDriverProvider,
模塊化約定官方原文:
A service provider that is developed in a module must be specified in a provides directive in the module declaration. The provides directive specifies both the service and the service provider; this helps to locate the provider when another module, with a uses directive for the service, obtains a service loader for the service. It is strongly recommended that the module does not export the package containing the service provider. There is no support for a module specifying, in a provides directive, a service provider in another module.
A service provider that is developed in a module has no control over when it is instantiated, since that occurs at the behest of the application, but it does have control over how it is instantiated:
If the service provider declares a provider method, then the service loader invokes that method to obtain an instance of the service provider. A provider method is a public static method named "provider" with no formal parameters and a return type that is assignable to the service's interface or class.
In this case, the service provider itself need not be assignable to the service's interface or class.
If the service provider does not declare a provider method, then the service provider is instantiated directly, via its provider constructor. A provider constructor is a public constructor with no formal parameters.
In this case, the service provider must be assignable to the service's interface or class
A service provider that is deployed as an automatic module on the application module path must have a provider constructor. There is no support for a provider method in this case.
As an example, suppose a module specifies the following directives:
provides com.example.CodecFactory with com.example.impl.StandardCodecs;
provides com.example.CodecFactory with com.example.impl.ExtendedCodecsFactory;
where
com.example.CodecFactory is the two-method service from earlier.
com.example.impl.StandardCodecs is a public class that implements CodecFactory and has a public no-args constructor.
com.example.impl.ExtendedCodecsFactory is a public class that does not implement CodecFactory, but it declares a public static no-args method named "provider" with a return type of CodecFactory.
A service loader will instantiate StandardCodecs via its constructor, and will instantiate ExtendedCodecsFactory by invoking its provider method. The requirement that the provider constructor or provider method is public helps to document the intent that the class (that is, the service provider) will be instantiated by an entity (that is, a service loader) which is outside the class's package.
組態檔約定
組態檔約定適用于專案沒有模塊化的情況,需要在 classpath 下的 META-INF/services/ 目錄里創建一個以服務介面命名的檔案,這個檔案里的內容就是這個介面的具體的實作類,
下文同樣以一個自定義的 java.sql.Driver 服務提供者(也可以自己隨意再另外一個模塊定義一個介面)為例,展示 SPI 在 java 組態檔約定下的使用方式,
1. 示例專案目錄結構:
本文提供了一個完整的例子用于測驗主要包含三個檔案,TestDriverProvider(自定義的 Driver 服務提供者,和上文一致),Main(用于除錯以及輸出結果,和上文一致),META-INF/services/java.sql.Driver 檔案(用于指定服務提供著的位置)
2. 示例檔案內容
TestDriverProvider 和 Main 與上文中均一致,不再次詳述,此處僅僅展示 META-INF/services/java.sql.Driver 檔案的內容,該檔案只包含一行內容:
com.wangzemin.learning.learning.provider.TestDriverProvider
3. 示例的輸出
Get class:Lcom/wangzemin/learning/provider/TestDriverProvider;
由輸出可以看到,ServiceLoader 可以成功定位到 TestDriverProvider,
組態檔約定官方原文
A service provider that is packaged as a JAR file for the class path is identified by placing a provider-configuration file in the resource directory META-INF/services. The name of the provider-configuration file is the fully qualified binary name of the service. The provider-configuration file contains a list of fully qualified binary names of service providers, one per line.
For example, suppose the service provider com.example.impl.StandardCodecs is packaged in a JAR file for the class path. The JAR file will contain a provider-configuration file named:
META-INF/services/com.example.CodecFactory
that contains the line:
com.example.impl.StandardCodecs # Standard codecs
The provider-configuration file must be encoded in UTF-8. Space and tab characters surrounding each service provider's name, as well as blank lines, are ignored. The comment character is '#' ('\u0023' NUMBER SIGN); on each line all characters following the first comment character are ignored. If a service provider class name is listed more than once in a provider-configuration file then the duplicate is ignored. If a service provider class is named in more than one configuration file then the duplicate is ignored.
A service provider that is mentioned in a provider-configuration file may be located in the same JAR file as the provider-configuration file or in a different JAR file. The service provider must be visible from the class loader that is initially queried to locate the provider-configuration file; this is not necessarily the class loader which ultimately locates the provider-configuration file.
SPI 原理
上文講述了 SPI 的一些約定,那么有了這些約定之后,SPI 機制是如何定位到對應的服務提供者的類并進行加載的呢?SPI 服務的加載可以分為兩部分:
- 類全稱限定名的獲取,即知道哪些類是服務提供者,
- 類加載,把獲取到的類加載到記憶體中,涉及背景關系類加載器,
類限定名獲取
模塊化情況下
可以參考jigsaw 官方檔案,jigsaw 模塊化語法本身就支持 SPI 服務,通過 provide xxxx with yyyy,可以為 xxxx 服務指定一個服務提供者 yyyy,這個決議程序由 jigsaw 實作,
官方檔案說明:Services allow for loose coupling between service consumers modules and service providers modules.This example has a service consumer module and a service provider module:
- module com.socket exports an API for network sockets. The API is in package com.socket so this package is exported. The API is pluggable to allow for alternative implementations. The service type is class com.socket.spi.NetworkSocketProvider in the same module and thus package com.socket.spi is also exported.
- module org.fastsocket is a service provider module. It provides an implementation of com.socket.spi.NetworkSocketProvider. It does not export any packages.
配置的情況下
在指定配置的情況下,ServiceLoader.load 根據傳入的介面類,遍歷 META-INF/services 目錄下的以該類命名的檔案中的所有類,然再用類加載器加載這些服務,

類加載器加載
獲取到 SPI 服務實作類的檔案之后,就可以使用類加載器將對應的類加載到記憶體中, 問題在于,SPI 的介面是 Java 核心庫的一部分,是由引導類加載器來加載的;SPI 實作的 Java 類一般是由系統類加載器來加載的,引導類加載器是無法找到 SPI 的實作類的,因為它只加載 Java 的核心庫,它也不能代理給系統類加載器,因為它是系統類加載器的祖先類加載器,也就是說,類加載器的雙親委派模型無法解決這個問題,所以 java 采用了執行緒背景關系類加載器,破壞了“雙親委派模型”,可以在執行執行緒中拋棄雙親委派加載鏈模式,使程式可以逆向使用類加載器,從而實作 SPI 服務的加載,執行緒背景關系類加載器的實作如下:
- 在 ThreaLocal 中通過 setContextClassLoader?(ClassLoader cl)存盤當前執行緒中的類加載器,默認為 AppClassLoader,
- Java 核心庫中的程式在需要加載 SPI 實作類的時候,會首先通過 ThreaLocal 中的 getContextClassLoader?(ClassLoader cl)方法獲取背景關系類加載器,然后通過該類加載器加載 SPI 的實作類,
ServiceLoader
參考官方檔案,ServiceLoader 是用于加載 SPI 服務實作類的工具,可以處理 0 個、1 個或者多個服務提供商的情況,
官方說明:A facility to load implementations of a service.A service is a well-known interface or class for which zero, one, or many service providers exist. A service provider (or just provider) is a class that implements or subclasses the well-known interface or class. A ServiceLoader is an object that locates and loads service providers deployed in the run time environment at a time of an application’s choosing. Application code refers only to the service, not to service providers, and is assumed to be capable of differentiating between multiple service providers as well as handling the possibility that no service providers are located.
其主要方法為 public static ServiceLoader load?(Class service, ClassLoader loader),該方法根據需要加載的 SPI 介面和類加載器(默認情況為執行緒背景關系類加載器),生成一個 ServiceLoader,生成的 ServiceLoader 可以通過迭代器 Iterotor 或 stream 的方式獲取 SPI 的實作類,加載主要分為兩部分:模塊化的服務類加載和非模塊化的類加載,最后會對所有加載到的實作類排序,
注意:加載的服務類如果包含網路資源,可能會出現一些例外情況,
If the class path of the class loader includes remote network URLs then those URLs may be dereferenced in the process of searching for provider-configuration files.
This activity is normal, although it may cause puzzling entries to be created in web-server logs. If a web server is not configured correctly, however, then this activity may cause the provider-loading algorithm to fail spuriously.
A web server should return an HTTP 404 (Not Found) response when a requested resource does not exist. Sometimes, however, web servers are erroneously configured to return an HTTP 200 (OK) response along with a helpful HTML error page in such cases. This will cause a ServiceConfigurationError to be thrown when this class attempts to parse the HTML page as a provider-configuration file. The best solution to this problem is to fix the misconfigured web server to return the correct response code (HTTP 404) along with the HTML error page.
上文說到,SPI 可能有很多服務提供者,但是只有其中一些是有用的,這種情況下我們就需要對 ServiceLoader 獲取到的服務實作類進行過濾,比如,我們只需要 PNG 格式的 CodecFactory,那么我們就可以對對應的服務實作類添加一個自定義的@PNG 注解,然后通過下文過濾得到所需的服務提供者:
ServiceLoader<CodecFactory> loader = ServiceLoader.load(CodecFactory.class);
Set<CodecFactory> pngFactories = loader
.stream() // Note a below
.filter(p -> p.type().isAnnotationPresent(PNG.class)) // Note b
.map(Provider::get) // Note c
.collect(Collectors.toSet());
我是御狐神,歡迎大家關注我的微信公眾號

本文最先發布至微信公眾號,著作權所有,禁止轉載!
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/297990.html
標籤:其他
