1、什么是SPI?
SPI(Service Provider Interface)是JDK内置的服务发现机制,用在不同模块间通过接口调用服务,避免对具体服务服务接口具体实现类的耦合。比如JDBC的数据库驱动模块,不同数据库连接驱动接口相同但实现类不同,在使用SPI机制以前调用驱动代码需要直接在类里采用Class.forName(具体实现类全名)的方式调用,这样调用方依赖了具体的驱动实现,在替换驱动实现时要修改代码。而采用SPI机制后,在驱动jar包的META-INF/services下面新建一个驱动接口全名的UTF-8编码的文件,里面写上具体实现类的全名,这样调用方通过Java 的ServiceLoad接口动态的去加载接口的实现类,从而达到替换驱动实现不用修改代码的效果,如下代码:
建立四个工程:
spi-interface:
package com.springboot.spi;
public interface IShout {
void shout();
}
spi-cat:
package com.springboot.spi;
public class Cat implements IShout {
public void shout() {
System.out.println("miao miao");
}
}
com.springboot.spi.IShout:
spi-dog:
package com.springboot.spi;
public class Dog implements IShout {
public void shout() {
System.out.println("wang wang");
}
}
com.springboot.spi.IShout:
spi-core:
package com.springboot.spi;
import java.util.ServiceLoader;
public class SPIMain {
public static void spiTest(String[] args) {
ServiceLoader<IShout> shouts = ServiceLoader.load(IShout.class);
for (IShout s : shouts) {
s.shout();
}
}
}
下面建立再建立一个工程进行测试:
spi_test:
引入包:
package com.zy.spitest;
import com.springboot.spi.SPIMain;
public class Test {
public static void main(String[] args) {
SPIMain.spiTest(args);
}
}
输出:
引入全部实现的包:
2、使用场景
- JDBC加载不同类型的驱动
- SLF4J对log4j/logback的支持
- Spring中大量使用了SPI,比如:对servlet3.0规范对ServletContainerInitializer的实现、自动类型转换Type Conversion SPI(Converter SPI、Formatter SPI)等
- Dubbo中也大量使用SPI的方式实现框架的扩展, 不过它对java提供的原生SPI做了封装
- 更多应用场景需要大家一起去发现,或者自己使用SPI机制实现代码的解耦
以JDBC为例:
通常各大厂商(如Mysql、Oracle)会根据一个统一的规范(java.sql.Driver)开发各自的驱动实现逻辑。客户端使用jdbc时不需要去改变代码,直接引入不同的spi接口服务即可。
Mysql的则是com.mysql.jdbc.Drive;Oracle则是oracle.jdbc.driver.OracleDriver。
伪代码如下:
//注:从jdbc4.0之后无需这个操作,spi机制会自动找到相关的驱动实现
//Class.forName(driver);
//1.getConnection()方法,连接MySQL数据库。有可能注册了多个Driver,这里通过遍历成功连接后返回。
con = DriverManager.getConnection(mysqlUrl,user,password);
//2.创建statement类对象,用来执行SQL语句!!
Statement statement = con.createStatement();
//3.ResultSet类,用来存放获取的结果集!!
ResultSet rs = statement.executeQuery(sql);
DriverManager是jdbc里管理和注册不同数据库driver的工具类。针对一个数据库,可能会存在着不同的数据库驱动实现。我们在使用特定的驱动实现时,不希望修改现有的代码,而希望通过一个简单的配置就可以达到效果。 在使用mysql驱动的时候,会有一个疑问,DriverManager是怎么获得某确定驱动类的?我们在运用Class.forName("com.mysql.jdbc.Driver")加载mysql驱动后,就会执行其中的静态代码把driver注册到DriverManager中,以便后续的使用。
Driver实现:
驱动的类的静态代码块中,调用DriverManager的注册驱动方法new一个自己当参数传给驱动管理器。
package com.mysql.jdbc;
import java.sql.DriverManager;
import java.sql.SQLException;
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!");
}
}
}
Mysql DriverManager实现
/**
* Load the initial JDBC drivers by checking the System property
* jdbc.properties and then use the {@code ServiceLoader} mechanism
*/
static {
loadInitialDrivers();
println("JDBC DriverManager initialized");
}
可以看到其内部的静态代码块中有一个loadInitialDrivers
方法,loadInitialDrivers
用法用到了上文提到的spi工具类ServiceLoader
,完成了引入的数据库驱动的查找及载入:
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;
}
//如果spi 存在将使用spi方式完成提供的Driver的加载
// If the driver is packaged as a Service Provider, load it.
// Get all the drivers through the classloader
// exposed as a java.sql.Driver.class service.
// ServiceLoader.load() replaces the sun.misc.Providers()
AccessController.doPrivileged(new PrivilegedAction<Void>() {
public Void run() {
//查找具体的provider,就是在META-INF/services/***.Driver文件中查找具体的实现。
ServiceLoader<Driver> loadedDrivers = ServiceLoader.load(Driver.class);
Iterator<Driver> driversIterator = loadedDrivers.iterator();
/* Load these drivers, so that they can be instantiated.
* It may be the case that the driver class may not be there
* i.e. there may be a packaged driver with the service class
* as implementation of java.sql.Driver but the actual class
* may be missing. In that case a java.util.ServiceConfigurationError
* will be thrown at runtime by the VM trying to locate
* and load the service.
*
* Adding a try catch block to catch those runtime errors
* if driver not available in classpath but it's
* packaged as service and that service is there in classpath.
*/
//查找具体的实现类的全限定名称
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);
}
}
主要看一下核心的代码段:
//java.util.serviceLoader.java
ServiceLoader<Driver> loadedDrivers = ServiceLoader.load(Driver.class);
Iterator<Driver> driversIterator = loadedDrivers.iterator();
try{
//查找具体的实现类的全限定名称
while(driversIterator.hasNext()) {
//加载并初始化实现
driversIterator.next();
}
} catch(Throwable t) {
// Do nothing
}
主要是通过ServiceLoader来完成的,我们按照执行顺序来看看ServiceLoader实现:
//初始化一个ServiceLoader,load参数分别是需要加载的接口class对象,当前类加载器
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);
}
遍历所有存在的service实现(ServiceLoader中)
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 static final String PREFIX = "META-INF/services/";
private boolean hasNextService() {
if (nextName != null) {
return true;
}
if (configs == null) {
try {
String fullName = PREFIX + service.getName();
//通过相对路径读取classpath中META-INF目录的文件,也就是读取服务提供者的实现类全限定名
if (loader == null)
configs = ClassLoader.getSystemResources(fullName);
else
configs = loader.getResources(fullName);
} catch (IOException x) {
fail(service, "Error locating configuration files", x);
}
}
//判断是否读取到实现类全限定名,比如mysql的“com.mysql.jdbc.Driver
”
while ((pending == null) || !pending.hasNext()) {
if (!configs.hasMoreElements()) {
return false;
}
pending = parse(service, configs.nextElement());
}
nextName = pending.next();//nextName保存,后续初始化实现类使用
return true;//查到了 返回true,接着调用next()
}
可以看到加载META-INF/services/ 文件夹下类名为文件名(这里相当于Driver.class.getName())的资源,然后将其加载到虚拟机。
public S next() {
if (acc == null) {//用来判断serviceLoader对象是否完成初始化
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 {
//加载字节码返回class对象.但并不去初始化(换句话就是说不去执行这个类中的static块与static变量初始化)
//
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 {
//初始化这个实现类.将会通过static块的方式触发实现类注册到DriverManager(其中组合了一个CopyOnWriteArrayList的registeredDrivers成员变量)中
S p = service.cast(c.newInstance());
providers.put(cn, p);//本地缓存 (全限定名,实现类对象)
return p;
} catch (Throwable x) {
fail(service,
"Provider " + cn + " could not be instantiated",
x);
}
throw new Error(); // This cannot happen
}
上一步中,Sp = service.cast(c.newInstance()) 将会导致具体实现者的初始化,比如mysqlJDBC,会触发如下代码:
//com.mysql.jdbc.Driver.java
......
private final static CopyOnWriteArrayList<DriverInfo> registeredDrivers = new CopyOnWriteArrayList<>();
......
static {
try {
//并发安全的想一个copyOnWriteList中方
java.sql.DriverManager.registerDriver(new Driver());
} catch (SQLException E) {
throw new RuntimeException("Can't register driver!");
}
}
/**
* Registers the given driver with the {@code DriverManager}.
* A newly-loaded driver class should call
* the method {@code registerDriver} to make itself
* known to the {@code DriverManager}. If the driver is currently
* registered, no action is taken.
*
* @param driver the new JDBC Driver that is to be registered with the
* {@code DriverManager}
* @param da the {@code DriverAction} implementation to be used when
* {@code DriverManager#deregisterDriver} is called
* @exception SQLException if a database access error occurs
* @exception NullPointerException if {@code driver} is null
* @since 1.8
*/
public static synchronized void registerDriver(java.sql.Driver driver,
DriverAction da)
throws SQLException {
/* Register the driver if it has not already been added to our list */
if(driver != null) {
registeredDrivers.addIfAbsent(new DriverInfo(driver, da));
} else {
// This is for compatibility with the original DriverManager
throw new NullPointerException();
}
println("registerDriver: " + driver);
}
将自己注册到驱动管理器的驱动列表中
public class DriverManager {
// List of registered JDBC drivers
private final static CopyOnWriteArrayList<DriverInfo> registeredDrivers = new CopyOnWriteArrayList<>();