Java中SPI機制的實現詳解
簡介
SPI(Service Provider Interface),是 JDK 內置的一種服務提供發(fā)現機制,可以用來啟用框架擴展和替換組件,核心思想是解耦。比如java.sql.Driver
接口,其他不同廠商可以針對同一接口做出不同的實現,MySQL 和 PostgreSQL 都有不同的實現提供給用戶。
當服務提供者提供了一種接口的實現后,需要在 classpath 下的 META-INF/services/
目錄下創(chuàng)建一個以服務接口命名的文件,文件的內容就是接口的具體實現類。
當使用該服務時,掃描 META-INF/services/
下配置文件,就可以加載類使用該服務。JDK 中查找服務的工具類是:java.util.ServiceLoader
。
以 MySQL 驅動為例:
源碼實現
以上面連接數據庫作為示例,看看 java8 SPI 怎么實現的。
入口在 java.sql.DriverManager
類中:
static { loadInitialDrivers(); println("JDBC DriverManager initialized"); } 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; } // 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() { 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); } } }
上面的代碼主要步驟是:
- 從系統變量中獲取有關驅動的定義。
- 使用 SPI 來獲取驅動的實現。
- 遍歷使用 SPI 獲取到的具體實現,實例化各個實現類。
- 根據第一步獲取到的驅動列表來實例化具體實現類。
主要關注第2,3步,第 2 步使用 SPI 獲取驅動的實現,對應實現:
ServiceLoader<Driver> loadedDrivers = ServiceLoader.load(Driver.class);
這里沒有去 META-INF/services
目錄下查找配置文件,也沒有加載具體實現類,只是封裝了接口類型和類加載器,并初始化了一個迭代器。
接著看第三步,遍歷使用 SPI 獲取到的具體實現,實例化各個實現類,對應的代碼如下:
// 獲取迭代器 Iterator<Driver> driversIterator = loadedDrivers.iterator(); // 遍歷所有的驅動實現 while(driversIterator.hasNext()) { driversIterator.next(); }
在遍歷的時候,首先調用driversIterator.hasNext()
方法,這里會搜索 classpath 下以及jar包中所有的META-INF/services
目錄下的java.sql.Driver
文件,并找到文件中的實現類的名字,此時并沒有實例化具體的實現類。
然后是調用driversIterator.next();
方法,此時就會根據驅動名字具體實例化各個實現類了。具體的掃描加載源碼見java.util.ServiceLoader
方法。
以上就是Java中SPI機制的實現詳解的詳細內容,更多關于Java SPI機制的資料請關注腳本之家其它相關文章!
相關文章
詳解Spring學習總結——Spring實現AOP的多種方式
這篇文章主要介紹了詳解Spring學習總結——Spring實現AOP的多種方式,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-01-01MyBatis異常-Property ''configLocation'' not specified, using d
今天小編就為大家分享一篇關于MyBatis異常-Property 'configLocation' not specified, using default MyBatis Configuration,小編覺得內容挺不錯的,現在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2019-03-03