Class.forName("com.mysql.jdbc.Driver") 什么作用、SPI

 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是什么?

要使用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

 

posted @ 2019-01-28 20:58  清晨_  阅读(19345)  评论(0编辑  收藏  举报