在學習SPI
之前卓缰,在了解一下API
(應用程序接口)慌盯,API就是服務方定義好接口和實現(xiàn)枫耳,然后提供暴露一個接口給調用方乏矾。那什么是SPI
呢?
SPI介紹
SPI
迁杨,全稱為 Service Provider Interface
钻心,是一種服務發(fā)現(xiàn)機制。它通過在classpath
路徑下的META-INF/services
文件夾查找文件铅协,自動加載文件里所定義的類捷沸。Java自身提供的服務發(fā)現(xiàn)機制,是掃描META-INF/services
文件夾文件定義的類狐史。但是痒给,也可以自己實現(xiàn)SPI
功能,掃描不同的文件夾文件骏全,像Dubbo
的SPI
機制和SpirngBoot
的SPI
機制苍柏,都是自己實現(xiàn)的SPI
功能,這為很多框架拓展功能提供了更多的可能性姜贡。
SPI
可以讓開發(fā)者拓展JDK
自身或者框架本身的功能,就是說開發(fā)者是服務實現(xiàn)方试吁,而JDK
或者框架是服務調用方。
簡而言之楼咳,就是指定那個目錄下熄捍,通過全限定類名去加載對應的類。
思考母怜,為什么需要SPI
思考一個問題余耽,有這樣一個需求,需要為某個開源框架或者已有的系統(tǒng)拓展一下功能苹熏。
比較常見的做法可能是在原來的代碼進行修改碟贾,然后重新編譯打包再發(fā)布币喧。
那有沒有方法可以不修改原來代碼就可以進行拓展呢?答案就是SPI
袱耽,這要求原來提供框架的開發(fā)者粱锐,使用SPI
,定義接口(interface
)或者抽象類(abstract class
), 以及實現(xiàn)了服務接口的具體類扛邑。
在使用中怜浅,框架提供接口,框架提供基礎的實現(xiàn)類蔬崩,開發(fā)者可以去拓展自己的實現(xiàn)類恶座。其中實現(xiàn)類的定義需要放在META-INF/services
下面, 在運行時框架會掃描服務配置文件下面的實現(xiàn)類,從而框架就可以調用沥阳。
使用實例
定義一個接口
public interface SPIService {
void service();
}
原系統(tǒng)調用
public class SPIServiceTest {
public static void main(String[] args) {
ServiceLoader<SPIService> spiServices = ServiceLoader.load(SPIService.class);
Iterator<SPIService> iterator = spiServices.iterator();
while (iterator.hasNext()) {
SPIService next = iterator.next();
next.service();
}
}
}
實現(xiàn)類1
public class SPIServiceA implements SPIService {
@Override
public void service() {
System.out.println("SPIServiceA");
}
}
實現(xiàn)類2
public class SPIServiceB implements SPIService {
@Override
public void service() {
System.out.println("SPIServiceB");
}
}
在resource
下面新建META-INF/services
目錄跨琳,然后新建文件com.spi.learn.service.SPIService
文件內容
com.spi.learn.service.SPIServiceA
com.spi.learn.service.SPIServiceB
JDK應用場景——Driver
在java.sql.DriverManager
類的loadInitialDrivers()
方法中
private static void loadInitialDrivers() {
....
AccessController.doPrivileged(new PrivilegedAction<Void>() {
public Void run() {
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;
}
});
....
}
其中ServiceLoader.load(Driver.class)
會去加載META-INF/services
目錄下,所有實現(xiàn)了Driver
接口的類桐罕,因此在mysql中實現(xiàn)了Driver
接口的類會被加載脉让,然后執(zhí)行靜態(tài)塊,這樣子就實現(xiàn)了不同數(shù)據(jù)庫的驅動注冊功炮。
com.mysql.jdbc.Driver
public class Driver extends NonRegisteringDriver implements java.sql.Driver {
//
// Register ourselves with the DriverManager
// static塊溅潜,執(zhí)行這行Class.forName("com.mysql.jdbc.Driver");的時候,會調用static塊
static {
try {
java.sql.DriverManager.registerDriver(new Driver());
} catch (SQLException E) {
throw new RuntimeException("Can't register driver!");
}
}
/**
* Construct a new driver and register it with DriverManager
*
* @throws SQLException
* if a database error occurs.
*/
public Driver() throws SQLException {
// Required for Class.forName().newInstance()
}
}