人生有涯,学海无涯
一、SPI是什么
SPI是相对API而言的。
API指的是应用对服务调用方提供的接口,用于提供某种服务、功能,面向的是服务调用方。
SPI指的是应用对服务实现方提供的接口,用于实现某种服务、功能,面向的是服务实现方
二、SPI机制
SPI(Service Provider Interface)是JDK内置的一种服务提供发现机制。
在平时开发中我们其实已经接触到,只不过一般开发真的用不上,像jdbc、apache logging等都用到SPI机制
这些SPI的接口是由Java核心库来提供,而SPI的实现则是作为Java应用所依赖的jar包被包含进类路径(CLASSPATH)中。例如:JDBC的实现mysql就是通过maven被依赖进来。
那么问题来了,SPI的接口是Java核心库的一部分,是由引导类加载器(Bootstrap Classloader)来加载的。SPI的实现类是由系统类加载器(System ClassLoader)来加载的。
引导类加载器在加载时是无法找到SPI的实现类的,因为双亲委派模型中规定,引导类加载器BootstrapClassloader无法委派系统类加载器AppClassLoader来加载。这时候,该如何解决此问题?
线程上下文类加载由此诞生,它的出现也破坏了类加载器的双亲委派模型,使得程序可以进行逆向类加载。
从JDBC案例分析:
Connection conn = java.sql.DriverManager.getConnection(url, "name", "password");
平时按照上述获取数据库连接,接着看DriverManager类
static {
loadInitialDrivers();
println("JDBC DriverManager initialized");
}
在DriverManager类中有一个静态代码块。很明显会调用loadInitialDrivers,接着loadInitialDrivers方法看
private static void loadInitialDrivers() {
String drivers;
try {
drivers = AccessController.doPrivileged(new PrivilegedAction<String>() {
public String run() {
return System.getProperty("jdbc.drivers");
}
});
} catch (Exception ex) {
drivers = null;
}
AccessController.doPrivileged(new PrivilegedAction<Void>() {
public Void run() {
ServiceLoader<Driver> loadedDrivers = ServiceLoader.load(Driver.class);
Iterator<Driver> driversIterator = loadedDrivers.iterator();
try{
while(driversIterator.hasNext()) {
driversIterator.next();
}
} catch(Throwable t) {
// Do nothing
}
return null;
}
});
println("DriverManager.initialize: jdbc.drivers = " + drivers);
if (drivers == null || drivers.equals("")) {
return;
}
String[] driversList = drivers.split(":");
println("number of Drivers:" + driversList.length);
for (String aDriver : driversList) {
try {
println("DriverManager.Initialize: loading " + aDriver);
Class.forName(aDriver, true,
ClassLoader.getSystemClassLoader());
} catch (Exception ex) {
println("DriverManager.Initialize: load failed: " + ex);
}
}
}
关键的信息在于ServiceLoader这个工具类,它是jdk提供服务实现查找的一个工具类:java.util.ServiceLoader。使用SPI机制就会用到它来进行服务实现
上述的Driver是在java.sql.Driver包,由jdk提供规范,它是一个接口。那其他厂商是如何实现?
maven引入mysql的依赖会将jar自动加入到类路径/CLASSPATH下
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
而它就提供了SPI机制配置文件(必须是类路径下的META-INF/services路径)
提供的服务实现刚好就是我们引入的mysql包的Driver
文件名需要和接口全限定类名一致java.sql.Driver
com.mysql.cj.jdbc.Driver需要实现java.sql.Driver
public class Driver extends NonRegisteringDriver implements java.sql.Driver {
public Driver() throws SQLException {
}
static {
try {
DriverManager.registerDriver(new Driver());
} catch (SQLException var1) {
throw new RuntimeException("Can't register driver!");
}
}
}
线程上下文类加载
在最开始获取数据库连接 的时候,getConnection()方法:
// Worker method called by the public getConnection() methods.
private static Connection getConnection(
String url, java.util.Properties info, Class<?> caller) throws SQLException {
/*
* When callerCl is null, we should check the application's
* (which is invoking this class indirectly)
* classloader, so that the JDBC driver class outside rt.jar
* can be loaded from here.
*/
ClassLoader callerCL = caller != null ? caller.getClassLoader() : null;
synchronized(DriverManager.class) {
// synchronize loading of the correct classloader.
if (callerCL == null) {
callerCL = Thread.currentThread().getContextClassLoader();
}
}
if(url == null) {
throw new SQLException("The url cannot be null", "08001");
}
println("DriverManager.getConnection(\"" + url + "\")");
// Walk through the loaded registeredDrivers attempting to make a connection.
// Remember the first exception that gets raised so we can reraise it.
SQLException reason = null;
for(DriverInfo aDriver : registeredDrivers) {
// If the caller does not have permission to load the driver then
// skip it.
if(isDriverAllowed(aDriver.driver, callerCL)) {
try {
println(" trying " + aDriver.driver.getClass().getName());
Connection con = aDriver.driver.connect(url, info);
if (con != null) {
// Success!
println("getConnection returning " + aDriver.driver.getClass().getName());
return (con);
}
} catch (SQLException ex) {
if (reason == null) {
reason = ex;
}
}
} else {
println(" skipping: " + aDriver.getClass().getName());
}
}
// if we got here nobody could connect.
if (reason != null) {
println("getConnection failed: " + reason);
throw reason;
}
println("getConnection: no suitable driver found for "+ url);
throw new SQLException("No suitable driver found for "+ url, "08001");
}
核心点:Thread.currentThread().getContextClassLoader()
三、SPI的使用
3.1、创建服务接口
package com.jw.spi;
public interface Fruit {
String getName();
}
3.2、创建多个服务实现
package com.jw.spi;
public class Apple implements Fruit {
@Override
public String getName() {
return "apple";
}
}
package com.jw.spi;
public class Banana implements Fruit {
@Override
public String getName() {
return "Banana";
}
}
这里的两个服务实现类,针对的是两个服务实现方,一方实现了Apple,另一方实现了Banana。
3.3、创建配置文件
在resource下创建/META-INF/services目录,在services目录下创建以服务接口全限定名为名称的文件:com.jw.spi.Fruit
文件内容为,当前服务实现的服务实现者类的全限定名
com.jw.spi.Apple
3.4、创建测试类
public class Test {
public static void main(String[] args) {
ServiceLoader<Fruit> s = ServiceLoader.load(Fruit.class);
Iterator<Fruit> it = s.iterator();
while(it.hasNext()){
System.out.println(it.next().getName());
}
}
}
执行结果为:
apple
四、SPI的实现原理
SPI的实现主要依靠的就是ServiceLoader类。使用该类加载接口类型(例如:Fruit.class)
ServiceLoader<Fruit> s = ServiceLoader.load(Fruit.class);
虽然是一个load方法,但是并没有加载到指定的服务实现类,这里仅仅是对加载服务实现类做一些准备工作:
下面分析一下ServiceLoader类的源码:
public final class ServiceLoader<S>
implements Iterable<S>
{
// 扫描目录前缀
private static final String PREFIX = "META-INF/services/";
// 被加载的类或接口
private final Class<S> service;
// 用于定位、加载和实例化实现方实现的类的类加载器
private final ClassLoader loader;
// 上下文对象
private final AccessControlContext acc;
// 按照实例化的顺序缓存已经实例化的类
private LinkedHashMap<String,S> providers = new LinkedHashMap<>();
// 懒查找迭代器
private LazyIterator lookupIterator;
// 创建ServiceLoader
public static <S> ServiceLoader<S> load(Class<S> service) {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
return ServiceLoader.load(service, cl);
}
public static <S> ServiceLoader<S> load(Class<S> service,
ClassLoader loader)
{
return new ServiceLoader<>(service, loader);
}
private ServiceLoader(Class<S> svc, ClassLoader cl) {
// 为service赋值
service = Objects.requireNonNull(svc, "Service interface cannot be null");
// 为loader赋值
loader = (cl == null) ? ClassLoader.getSystemClassLoader() : cl;
// 为acc赋值
acc = (System.getSecurityManager() != null) ? AccessController.getContext() : null;
reload();
}
public void reload() {
// 清空providers缓存
providers.clear();
// 为lookupIterator赋值,其实就是创建一个LazyIterator延迟迭代器。
lookupIterator = new LazyIterator(service, loader);
}
// 私有内部类,提供对所有的service的类的加载与实例化
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;
}
....
}
然后创建迭代器:Iterator<Fruit> it = s.iterator();
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();
}
};
}
iterator方法中采用了匿名内部类的方式定义了一个新的迭代器,这个迭代器中每一个方法都是通过调用之前创建好的延迟迭代器lookupIterator来完成的
最后就是进行迭代加载了。
while(it.hasNext()){
System.out.println(it.next().getName());
}
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);
}
}
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;
}
hasNext方法调用了延迟迭代器的hasNext方法,内部调用了hasNextService方法,在这个方法中就会设法去找到指定名称(META-INF/services/+接口全限定名)的资源文件。并完成读取文件内容的操作。
然后执行it.next()操作,这个又会调用延迟迭代器的对应方法hasNext,内部调用了nextService方法,这个方法主要功能就是加载上面从文件中读取到的全限定名称表示的类。并生成实例,将实例保存到providers中。
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);
}
}
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());
// 将实例保存到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
}
五、总结
关于spi的详解到此就结束了,总结下spi能带来的好处:
- 不需要改动源码就可以实现扩展,解耦。
- 实现扩展对原来的代码几乎没有侵入性。
- 只需要添加配置就可以实现扩展,符合开闭原则。