1、手動調用Class.forName()
我們知道當我們連接MySQL數據庫時,會使用如下代碼:
1 try { 2 Class.forName("com.mysql.jdbc.Driver"); 3 connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "123456"); 4 } catch (Exception e) { 5 e.printStackTrace(); 6 }
那么Class.forName()有什么作用呢?
首先我們知道Class.forName() 方法要求JVM查找並加載指定的類到內存中,此時將"com.mysql.jdbc.Driver" 當做參數傳入,就是告訴JVM,去"com.mysql.jdbc"這個路徑下找Driver類,將其加載到內存中。
由於加載類文件時會執行其中的靜態代碼塊,其中Driver類的源碼如下
public class Driver extends NonRegisteringDriver implements java.sql.Driver { public Driver() throws SQLException { } static { try { DriverManager.registerDriver(new Driver());//首先new一個Driver對象,並將它注冊到DriverManage中 } catch (SQLException var1) { throw new RuntimeException("Can't register driver!"); } } }
接下來我們再看看這個DriverManager.registerDriver 方法:
public static synchronized void registerDriver(java.sql.Driver driver) throws SQLException { registerDriver(driver, null); }
繼續看這個registerDriver(driver, null) 方法
private final static CopyOnWriteArrayList<DriverInfo> registeredDrivers = new CopyOnWriteArrayList<>();// registeredDrivers 是一個支持並發的arraylist ...... public static void registerDriver(java.sql.Driver driver, DriverAction da) throws SQLException { if (driver != null) { //如果該驅動尚未注冊,那么將他添加到 registeredDrivers 中去。這是一個支持並發情況的特殊ArrayList registeredDrivers.addIfAbsent(new DriverInfo(driver, da)); } else { // This is for compatibility with the original DriverManager throw new NullPointerException(); } println("registerDriver: " + driver); }
此時,Class.forName(“com.mysql.jdbc.Driver”) 的工作就完成了,工作就是:將mysql驅動注冊到DriverManager中去。接下來我們看是怎么進行調用的
2、DriverManager.getConnection方法分析
注冊到DriverManager中之后,我們就可以通過DriverManager的getConnection方法獲得mysql的連接了:
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "123456");
接下來我們在看看這個getConnection方法:
@CallerSensitive public static Connection getConnection(String url, String user, String password) throws SQLException { .... return (getConnection(url, info, Reflection.getCallerClass())); }
同樣,調用了自身的 getConnection方法,繼續往下看
1 private static Connection getConnection( 2 String url, java.util.Properties info, Class<?> caller) throws SQLException { 3 ClassLoader callerCL = caller != null ? caller.getClassLoader() : null; 4 synchronized(DriverManager.class) { 5 // synchronize loading of the correct classloader. 6 if (callerCL == null) { 7 callerCL = Thread.currentThread().getContextClassLoader(); 8 } 9 } 10 // Walk through the loaded registeredDrivers attempting to make a connection. 11 // Remember the first exception that gets raised so we can reraise it. 12 SQLException reason = null; 13 14 for(DriverInfo aDriver : registeredDrivers) { 15 // If the caller does not have permission to load the driver then skip it. 16 if(isDriverAllowed(aDriver.driver, callerCL)) { 17 try { 18 Connection con = aDriver.driver.connect(url, info); 19 if (con != null) { 20 // Success! 21 return (con); 22 } 23 } catch (SQLException ex) { 24 if (reason == null) { 25 reason = ex; 26 } 27 } 28 } else { 29 println("skipping: " + aDriver.getClass().getName()); 30 } 31 } 32 33 // if we got here nobody could connect. 34 if (reason != null) { 35 println("getConnection failed: " + reason); 36 throw reason; 37 } 38 throw new SQLException("No suitable driver found for "+ url, "08001"); 39 }
可以看到它對上文提到的靜態變量 registeredDrivers 進行了遍歷,調用了connect(url, info)方法,這是一個接口,由各個不同的驅動自己實現。
/** * Attempts to make a database connection to the given URL. * The driver should return "null" if it realizes it is the wrong kind * of driver to connect to the given URL. This will be common, as when * the JDBC driver manager is asked to connect to a given URL it passes * the URL to each loaded driver in turn. */ Connection connect(String url, java.util.Properties info) throws SQLException;
到此為止,我們就獲得了connection對象,現在就可以對數據庫進行操作了。
3、不手動注冊驅動也能使用JDBC [ 去除class.forName ]
在高版本的JDK,已經不需要手動調用class.forName方法了,在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()方法中看到以下一段代碼:
1 private static void loadInitialDrivers() { 2 String drivers; 3 try { 4 drivers = AccessController.doPrivileged(new PrivilegedAction<String>() { 5 public String run() { 6 return System.getProperty("jdbc.drivers"); 7 } 8 }); 9 } catch (Exception ex) { 10 drivers = null; 11 } 12 // If the driver is packaged as a Service Provider, load it. 13 // Get all the drivers through the classloader 14 // exposed as a java.sql.Driver.class service. 15 // ServiceLoader.load() replaces the sun.misc.Providers() 16 17 AccessController.doPrivileged(new PrivilegedAction<Void>() { 18 public Void run() { 19 20 ServiceLoader<Driver> loadedDrivers = ServiceLoader.load(Driver.class); 21 Iterator<Driver> driversIterator = loadedDrivers.iterator(); 22 23 /* Load these drivers, so that they can be instantiated. 24 * It may be the case that the driver class may not be there 25 * i.e. there may be a packaged driver with the service class 26 * as implementation of java.sql.Driver but the actual class 27 * may be missing. In that case a java.util.ServiceConfigurationError 28 * will be thrown at runtime by the VM trying to locate 29 * and load the service. 30 * 31 * Adding a try catch block to catch those runtime errors 32 * if driver not available in classpath but it's 33 * packaged as service and that service is there in classpath. 34 */ 35 try{ 36 while(driversIterator.hasNext()) { 37 driversIterator.next(); 38 } 39 } catch(Throwable t) { 40 // Do nothing 41 } 42 return null; 43 } 44 });
重點是第20行,ServiceLoader.load(Driver.class)
上面這行代碼可以把類路徑下所有jar包中META-INF/services/java.sql.Driver文件中定義的類加載上來,此類必須繼承自java.sql.Driver。
最后我們看一下第37行最后我們看一下Iterator的next()方法做了什么就完全懂了,通過next()方法調用了:
private S nextService() { if (!hasNextService()) throw new NoSuchElementException(); String cn = nextName; nextName = null; Class<?> c = null; try { c = Class.forName(cn, false, loader); //看這里,Class.forName() } 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.put(cn, p); return p; } catch (Throwable x) { fail(service, "Provider " + cn + " could not be instantiated", x); } throw new Error(); // This cannot happen }
我們看到了Class.forName,這樣是通過SPI的方式把用戶手動做的動作變成框架做。
4、SPI是什么?
-
在jar包的META-INF/services目錄下創建一個以"接口全限定名"為命名的文件,內容為實現類的全限定名
-
接口實現類所在的jar包在classpath下
-
主程序通過java.util.ServiceLoader動態狀態實現模塊,它通過掃描META-INF/services目錄下的配置文件找到實現類的全限定名,把類加載到JVM
-
SPI的實現類必須帶一個無參構造方法
接着我們看一下具體例子,首先定義一個SpiService,它是一個接口:
package org.xrq.test.spi; public interface SpiService { public void hello(); }
兩個實現類,分別為SpiServiceA與SpiServiceB
package org.xrq.test.spi; public class SpiServiceA implements SpiService {
@Override public void hello() { System.out.println("SpiServiceA.Hello"); } } package org.xrq.test.spi; public class SpiServiceB implements SpiService { @Override public void hello() { System.out.println("SpiServiceB.hello"); } }
接着我們建一個META-INF/services的文件夾,里面建一個file,file的名字是接口的全限定名org.xrq.test.spi.SpiService:
文件的內容是SpiService實現類SpiServiceA、SpiServiceB的全限定名:
org.xrq.test.spi.SpiServiceA
org.xrq.test.spi.SpiServiceB
這樣就大功告成了!然后我們寫個測試類自動加載一下這兩個類:
public class SpiTest { @Test public void testSpi() { ServiceLoader<SpiService> serviceLoader = ServiceLoader.load(SpiService.class); Iterator<SpiService> iterator = serviceLoader.iterator(); while (iterator.hasNext()) { SpiService spiService = iterator.next(); spiService.hello(); } } }
結果一目了然,調用了hello()方法:
SpiServiceA.Hello
SpiServiceB.hello
這就是SPI的使用示例,接着我們看一下SPI在實際場景中的應用。
5、對SPI的理解
我理解的SPI其實是一種可插拔技術的總稱,最簡單的例子就是USB,廠商提供了USB的標准,廠家根據USB的標准制造自己的外設,例如鼠標、鍵盤、游戲手柄等等,但是USB標准具體在電腦中是怎么用的,廠家就不需要管了。
回到我們的代碼中也是一樣的道理。當我們開發一個框架的時候,除了保證基本的功能外,最重要的一個點是什么?我認為最重要的應該是松耦合,即對擴展開放、對修改關閉,保證框架實現對於使用者來說是黑盒。
框架不可能做好所有的事情,只能把共性的部分抽離出來進行流程化,松耦合實現的核心就是定義好足夠松散的接口,或者可以理解是擴展點,具體的擴展點讓使用者去實現,這樣不同的擴展就不需要修改源代碼或者對框架進行定制,這就是面向接口編程的好處。
回到我們框架的部分來說:
-
JDK對於SPI的實現是通過META-INF/services這個目錄 + ServiceLoader
-
Spring實現SPI的方式是留了N多的接口,例如BeanPostProcessor、InitializingBean、DisposableBean,我們只需要實現這些接口然后注入即可
對已有框架而言,我們可以通過框架給我們提供的擴展點擴展框架功能。對自己寫框架而言,記得SPI這個事情,留好足夠的擴展點,這將大大加強你寫的框架的擴展性。
轉載鏈接: https://blog.csdn.net/zt928815211/article/details/83420828
https://www.zhihu.com/question/22925738/answer/23088255
https://mp.weixin.qq.com/s/I1Nf8-sQ8wk5_RGnupJoSg