概述
關鍵詞:解耦,可拔插,面向接口編程,動態類加載。
本質:Java SPI 實際上是“基於接口的編程+策略模式+約定配置文件” 組合實現的動態加載機制,在JDK中提供了工具類:“java.util.ServiceLoader”來實現服務查找。
什麼是SPI ?
SPI 全稱:Service Provider Interface,是Java提供的一套用來被第三方實現或者擴展的接口,它可以用來啓用框架擴展和替換組件。
面向的對象的設計裏,我們一般推薦模塊之間基於接口編程,模塊之間不對實現類進行硬編碼。一旦代碼裏涉及具體的實現類,就違反了可拔插的原則,如果需要替換一種實現,就需要修改代碼。
爲了實現在模塊裝配的時候不用在程序裏動態指明,這就需要一種服務發現機制。java spi就是提供這樣的一個機制:爲某個接口尋找服務實現的機制。這有點類似IOC的思想,將裝配的控制權移到了程序之外。
SPI的作用就是爲被擴展的API尋找服務實現。
SPI(Service Provider Interface),是JDK內置的一種 服務提供發現機制,可以用來啓用框架擴展和替換組件,主要是被框架的開發人員使用,比如java.sql.Driver接口,其他不同廠商可以針對同一接口做出不同的實現,MySQL和PostgreSQL都有不同的實現提供給用戶,而Java的SPI機制可以爲某個接口尋zhao服務實現。Java中SPI機制主要思想是將裝配的控制權移到程序之外,在模塊化設計中這個機制尤其重要,其核心思想就是 解耦。
SPI整體機制圖如下:
當服務的提供者提供了一種接口的實現之後,需要在classpath下的META-INF/services/目錄裏創建一個以服務接口命名的文件,這個文件裏的內容就是這個接口的具體的實現類。當其他的程序需要這個服務的時候,就可以通過查找這個jar包(一般都是以jar包做依賴)的META-INF/services/中的配置文件,配置文件中有接口的具體實現類名,可以根據這個類名進行加載實例化,就可以使用該服務了。JDK中查找服務的實現的工具類是:java.util.ServiceLoader。
SPI 的不足
1.不能按需加載,需要遍歷所有的實現,並實例化,然後在循環中才能找到我們需要的實現。如果不想用某些實現類,或者某些類實例化很耗時,它也被載入並實例化了,這就造成了浪費。
2.獲取某個實現類的方式不夠靈活,只能通過 Iterator 形式獲取,不能根據某個參數來獲取對應的實現類。(Spring 的BeanFactory,ApplicationContext 就要高級一些了。)
3.多個併發多線程使用 ServiceLoader 類的實例是不安全的。
API 與 SPI
SPI與API區別:
API是調用並用於實現目標的類、接口、方法等的描述;
SPI是擴展和實現以實現目標的類、接口、方法等的描述;
換句話說,API 爲操作提供特定的類、方法,SPI 通過操作來符合特定的類、方法。
參考: https://stackoverflow.com/questions/2954372/difference-between-spi-and-api?answertab=votes#tab-top
SPI和API的使用場景解析:
- API (Application Programming Interface)在大多數情況下,都是實現方制定接口並完成對接口的實現,調用方僅僅依賴接口調用,且無權選擇不同實現。 從使用人員上來說,API 直接被應用開發人員使用。
- SPI (Service Provider Interface)是調用方來制定接口規範,提供給外部來實現,調用方在調用時則選擇自己需要的外部實現。 從使用人員上來說,SPI 被框架擴展人員使用。
SPI 應用場景
SPI擴展機制應用場景有很多,比如Common-Logging,JDBC,Dubbo等等。
SPI流程:
有關組織和公式定義接口標準
第三方提供具體實現: 實現具體方法, 配置 META-INF/services/${interface_name} 文件
開發者使用
比如JDBC場景下:
首先在Java中定義了接口java.sql.Driver,並沒有具體的實現,具體的實現都是由不同廠商提供。
在MySQL的jar包mysql-connector-java-6.0.6.jar中,可以找到META-INF/services目錄,該目錄下會有一個名字爲java.sql.Driver的文件,文件內容是com.mysql.cj.jdbc.Driver,這裏面的內容就是針對Java中定義的接口的實現。
同樣在PostgreSQL的jar包PostgreSQL-42.0.0.jar中,也可以找到同樣的配置文件,文件內容是org.postgresql.Driver,這是PostgreSQL對Java的java.sql.Driver的實現。
項目案例
Java 工程目錄:
下面我們來簡單實現一個 JDK 的SPI的簡單實現。
Java代碼開發
首先第一步,定義一個接口:
Phone.java
package com.light.sword;
/**
* @author: Jack
* 2021/1/31 上午1:44
*/
public interface Phone {
String getSystemInfo();
}
這個接口分別有兩個實現:
Huawei.java
package com.light.sword;
/**
* @author: Jack
* 2021/1/31 上午1:48
*/
public class Huawei implements Phone {
@Override
public String getSystemInfo() {
return "Hong Meng";
}
}
IPhone.java
package com.light.sword;
/**
* @author: Jack
* 2021/1/31 上午1:48
*/
public class IPhone implements Phone {
@Override
public String getSystemInfo() {
return "iOS";
}
}
約定配置:新建 META-INF/services 目錄
注意:這個META-INF/services 目錄是寫死的約定,在
java.util.ServiceLoader
源碼實現中, java.util.ServiceLoader#PREFIX 可以看到這個目錄的硬編碼。
然後需要在resources目錄下新建 META-INF/services
目錄,並且在這個目錄下新建一個與上述接口的全限定名一致的文件:
com.light.sword.Phone (這是一個文件,是的,一切皆是文件。)
在這個文件中寫入接口的實現類的全限定名(文件 com.light.sword.Phone 中寫死的內容):
com.light.sword.Huawei
com.light.sword.IPhone
如下圖所示:
加載實現類並調用服務
這時,通過ServiceLoader 加載實現類並調用服務:
Main.java
package com.light.sword;
import java.util.ServiceLoader;
public class Main {
public static void main(String[] args) {
ServiceLoader<Phone> phoneServiceLoader = ServiceLoader.load(Phone.class);
phoneServiceLoader.forEach(provider -> {
String systemInfo = provider.getSystemInfo();
System.out.println(systemInfo);
});
}
}
輸出如下:
Hong Meng
iOS
工程源代碼:https://gitee.com/universsky/java-spi-demo
這樣一個簡單的 Java SPI 的demo就完成了。可以看到其中最爲核心的就是通過一系列的約定(其實,就是按照人家 java.util.ServiceLoader
的規範標準來), 然後,通過ServiceLoader 這個類來加載具體的實現類,進而調用實現類的服務。
知識拓展:
其實,我們在Spring框架中,可以通過
component-scan
標籤來對指定包路徑進行掃描,只要掃到 Spring 制定的@Service
、@Controller
等註解,spring自動會把它注入容器。 這就相當於spring制定了註解規範,我們按照這個註解規範開發相應的實現類或controller,spring並不需要感知我們是怎麼實現的,他只需要根據註解規範和scan標籤注入相應的bean,這正是 spi 理念的體現。
SPI 實現原理解析
首先,ServiceLoader實現了Iterable接口,所以它有迭代器的屬性,這裏主要都是實現了迭代器的hasNext和next方法。這裏主要都是調用的lookupIterator的相應hasNext和next方法,lookupIterator是懶加載迭代器。
其次,LazyIterator中的hasNext方法,靜態變量PREFIX就是”META-INF/services/”目錄,這也就是爲什麼需要在classpath下的META-INF/services/目錄裏創建一個以服務接口命名的文件。
最後,通過反射方法Class.forName()加載類對象,並用newInstance方法將類實例化,並把實例化後的類緩存到providers對象中,(LinkedHashMap<String,S>類型) 然後返回實例對象。
java.util.ServiceLoader.java 源代碼如下:
package java.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.security.AccessController;
import java.security.AccessControlContext;
import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
// ServiceLoader實現了Iterable接口,可以遍歷所有的服務實現者
public final class ServiceLoader<S> implements Iterable<S>
{
// 約定的配置文件的存放目錄
private static final String PREFIX = "META-INF/services/";
// The class or interface representing the service being loaded
private final Class<S> service;
// The class loader used to locate, load, and instantiate providers
private final ClassLoader loader;
// The access control context taken when the ServiceLoader is created
private final AccessControlContext acc;
// Cached providers, in instantiation order
private LinkedHashMap<String,S> providers = new LinkedHashMap<>();
// The current lazy-lookup iterator
private LazyIterator lookupIterator;
/**
* Clear this loader's provider cache so that all providers will be
* reloaded.
*
* <p> After invoking this method, subsequent invocations of the {@link
* #iterator() iterator} method will lazily look up and instantiate
* providers from scratch, just as is done by a newly-created loader.
*
* <p> This method is intended for use in situations in which new providers
* can be installed into a running Java virtual machine.
*/
public void reload() {
providers.clear();
lookupIterator = new LazyIterator(service, loader);
}
private ServiceLoader(Class<S> svc, ClassLoader cl) {
service = Objects.requireNonNull(svc, "Service interface cannot be null");
loader = (cl == null) ? ClassLoader.getSystemClassLoader() : cl;
acc = (System.getSecurityManager() != null) ? AccessController.getContext() : null;
reload();
}
private static void fail(Class<?> service, String msg, Throwable cause)
throws ServiceConfigurationError
{
throw new ServiceConfigurationError(service.getName() + ": " + msg,
cause);
}
private static void fail(Class<?> service, String msg)
throws ServiceConfigurationError
{
throw new ServiceConfigurationError(service.getName() + ": " + msg);
}
private static void fail(Class<?> service, URL u, int line, String msg)
throws ServiceConfigurationError
{
fail(service, u + ":" + line + ": " + msg);
}
// Parse a single line from the given configuration file, adding the name
// on the line to the names list.
//
private int parseLine(Class<?> service, URL u, BufferedReader r, int lc,
List<String> names)
throws IOException, ServiceConfigurationError
{
String ln = r.readLine();
if (ln == null) {
return -1;
}
int ci = ln.indexOf('#');
if (ci >= 0) ln = ln.substring(0, ci);
ln = ln.trim();
int n = ln.length();
if (n != 0) {
if ((ln.indexOf(' ') >= 0) || (ln.indexOf('\t') >= 0))
fail(service, u, lc, "Illegal configuration-file syntax");
int cp = ln.codePointAt(0);
if (!Character.isJavaIdentifierStart(cp))
fail(service, u, lc, "Illegal provider-class name: " + ln);
for (int i = Character.charCount(cp); i < n; i += Character.charCount(cp)) {
cp = ln.codePointAt(i);
if (!Character.isJavaIdentifierPart(cp) && (cp != '.'))
fail(service, u, lc, "Illegal provider-class name: " + ln);
}
if (!providers.containsKey(ln) && !names.contains(ln))
names.add(ln);
}
return lc + 1;
}
// Parse the content of the given URL as a provider-configuration file.
//
// @param service
// The service type for which providers are being sought;
// used to construct error detail strings
//
// @param u
// The URL naming the configuration file to be parsed
//
// @return A (possibly empty) iterator that will yield the provider-class
// names in the given configuration file that are not yet members
// of the returned set
//
// @throws ServiceConfigurationError
// If an I/O error occurs while reading from the given URL, or
// if a configuration-file format error is detected
//
private Iterator<String> parse(Class<?> service, URL u)
throws ServiceConfigurationError
{
InputStream in = null;
BufferedReader r = null;
ArrayList<String> names = new ArrayList<>();
try {
in = u.openStream();
r = new BufferedReader(new InputStreamReader(in, "utf-8"));
int lc = 1;
while ((lc = parseLine(service, u, r, lc, names)) >= 0);
} catch (IOException x) {
fail(service, "Error reading configuration file", x);
} finally {
try {
if (r != null) r.close();
if (in != null) in.close();
} catch (IOException y) {
fail(service, "Error closing configuration file", y);
}
}
return names.iterator();
}
// Private inner class implementing fully-lazy provider lookup
//
private class LazyIterator
implements Iterator<S>
{
Class<S> service;
ClassLoader loader;
Enumeration<URL> configs = null;
Iterator<String> pending = null;
String nextName = null;
private LazyIterator(Class<S> service, ClassLoader loader) {
this.service = service;
this.loader = loader;
}
private boolean hasNextService() {
if (nextName != null) {
return true;
}
if (configs == null) {
try {
String fullName = PREFIX + service.getName();
if (loader == null)
configs = ClassLoader.getSystemResources(fullName);
else
configs = loader.getResources(fullName);
} catch (IOException x) {
fail(service, "Error locating configuration files", x);
}
}
while ((pending == null) || !pending.hasNext()) {
if (!configs.hasMoreElements()) {
return false;
}
pending = parse(service, configs.nextElement());
}
nextName = pending.next();
return true;
}
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());
// 放進 ServiceLoader的providers容器裏面
providers.put(cn, p);
return p;
} catch (Throwable x) {
fail(service,
"Provider " + cn + " could not be instantiated",
x);
}
throw new Error(); // This cannot happen
}
public boolean hasNext() {
if (acc == null) {
return hasNextService();
} else {
PrivilegedAction<Boolean> action = new PrivilegedAction<Boolean>() {
public Boolean run() { return hasNextService(); }
};
return AccessController.doPrivileged(action, acc);
}
}
public S next() {
if (acc == null) {
return nextService();
} else {
PrivilegedAction<S> action = new PrivilegedAction<S>() {
public S run() { return nextService(); }
};
return AccessController.doPrivileged(action, acc);
}
}
public void remove() {
throw new UnsupportedOperationException();
}
}
/**
* Lazily loads the available providers of this loader's service.
*
* <p> The iterator returned by this method first yields all of the
* elements of the provider cache, in instantiation order. It then lazily
* loads and instantiates any remaining providers, adding each one to the
* cache in turn.
*
* <p> To achieve laziness the actual work of parsing the available
* provider-configuration files and instantiating providers must be done by
* the iterator itself. Its {@link java.util.Iterator#hasNext hasNext} and
* {@link java.util.Iterator#next next} methods can therefore throw a
* {@link ServiceConfigurationError} if a provider-configuration file
* violates the specified format, or if it names a provider class that
* cannot be found and instantiated, or if the result of instantiating the
* class is not assignable to the service type, or if any other kind of
* exception or error is thrown as the next provider is located and
* instantiated. To write robust code it is only necessary to catch {@link
* ServiceConfigurationError} when using a service iterator.
*
* <p> If such an error is thrown then subsequent invocations of the
* iterator will make a best effort to locate and instantiate the next
* available provider, but in general such recovery cannot be guaranteed.
*
* <blockquote style="font-size: smaller; line-height: 1.2"><span
* style="padding-right: 1em; font-weight: bold">Design Note</span>
* Throwing an error in these cases may seem extreme. The rationale for
* this behavior is that a malformed provider-configuration file, like a
* malformed class file, indicates a serious problem with the way the Java
* virtual machine is configured or is being used. As such it is
* preferable to throw an error rather than try to recover or, even worse,
* fail silently.</blockquote>
*
* <p> The iterator returned by this method does not support removal.
* Invoking its {@link java.util.Iterator#remove() remove} method will
* cause an {@link UnsupportedOperationException} to be thrown.
*
* @implNote When adding providers to the cache, the {@link #iterator
* Iterator} processes resources in the order that the {@link
* java.lang.ClassLoader#getResources(java.lang.String)
* ClassLoader.getResources(String)} method finds the service configuration
* files.
*
* @return An iterator that lazily loads providers for this loader's
* service
*/
public Iterator<S> iterator() {
return new Iterator<S>() {
Iterator<Map.Entry<String,S>> knownProviders
= providers.entrySet().iterator();
public boolean hasNext() {
if (knownProviders.hasNext())
return true;
return lookupIterator.hasNext();
}
public S next() {
if (knownProviders.hasNext())
return knownProviders.next().getValue();
return lookupIterator.next();
}
public void remove() {
throw new UnsupportedOperationException();
}
};
}
/**
* Creates a new service loader for the given service type and class
* loader.
*
* @param <S> the class of the service type
*
* @param service
* The interface or abstract class representing the service
*
* @param loader
* The class loader to be used to load provider-configuration files
* and provider classes, or <tt>null</tt> if the system class
* loader (or, failing that, the bootstrap class loader) is to be
* used
*
* @return A new service loader
*/
public static <S> ServiceLoader<S> load(Class<S> service,
ClassLoader loader)
{
return new ServiceLoader<>(service, loader);
}
/**
* Creates a new service loader for the given service type, using the
* current thread's {@linkplain java.lang.Thread#getContextClassLoader
* context class loader}.
*
* <p> An invocation of this convenience method of the form
*
* <blockquote><pre>
* ServiceLoader.load(<i>service</i>)</pre></blockquote>
*
* is equivalent to
*
* <blockquote><pre>
* ServiceLoader.load(<i>service</i>,
* Thread.currentThread().getContextClassLoader())</pre></blockquote>
*
* @param <S> the class of the service type
*
* @param service
* The interface or abstract class representing the service
*
* @return A new service loader
*/
public static <S> ServiceLoader<S> load(Class<S> service) {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
return ServiceLoader.load(service, cl);
}
/**
* Creates a new service loader for the given service type, using the
* extension class loader.
*
* <p> This convenience method simply locates the extension class loader,
* call it <tt><i>extClassLoader</i></tt>, and then returns
*
* <blockquote><pre>
* ServiceLoader.load(<i>service</i>, <i>extClassLoader</i>)</pre></blockquote>
*
* <p> If the extension class loader cannot be found then the system class
* loader is used; if there is no system class loader then the bootstrap
* class loader is used.
*
* <p> This method is intended for use when only installed providers are
* desired. The resulting service will only find and load providers that
* have been installed into the current Java virtual machine; providers on
* the application's class path will be ignored.
*
* @param <S> the class of the service type
*
* @param service
* The interface or abstract class representing the service
*
* @return A new service loader
*/
public static <S> ServiceLoader<S> loadInstalled(Class<S> service) {
ClassLoader cl = ClassLoader.getSystemClassLoader();
ClassLoader prev = null;
while (cl != null) {
prev = cl;
cl = cl.getParent();
}
return ServiceLoader.load(service, prev);
}
/**
* Returns a string describing this service.
*
* @return A descriptive string
*/
public String toString() {
return "java.util.ServiceLoader[" + service.getName() + "]";
}
}
參考資料
https://www.cnblogs.com/jy107600/p/11464985.html
http://blog.itpub.net/69912579/viewspace-2656555/
https://segmentfault.com/a/1190000020422160