深入探究JDK的SPI机制

概念:SPI的全称service provider interface。是JDK内置的一种服务提供机制。一种典型的面向接口编程。JDK定义了一些接口规范,由服务提供者自定义扩展实现接口。

下面以JDBC为案例一探SPI机制的具体实现原理,直接上代码:

import java.sql.*;

public class JdkSpiMain {

    public static void main(String[] args) {
        Connection conn = null;
        try {
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/ test?useUnicode=true&characterEncoding=UTF-8", "test", "test");
            String sql = "select count(1) from test";
            PreparedStatement ps = conn.prepareStatement(sql);
            ResultSet resultSet = ps.executeQuery();
            while(resultSet.next()) {
                long count = resultSet.getLong(1);
                System.out.println("count : " + count);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != conn) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

pom.xml文件中引入mysql驱动包


    mysql
    mysql-connector-java
    runtime

运行结果

深入探究JDK的SPI机制_第1张图片

从上面运行结果可以看出,程序正常运行并按预期查询mysql库返回test表的总数量。

产生疑问:代码中并未引用和使用mysql驱动包中的任何类,程序是如何进行数据库操作的?

下面我们通过DriverManager源码来一探究竟:

代码中使用DirverManager的静态方法getConnection(url, username, password)获取的数据库链接,那么我们就来看看getConnection方法

@CallerSensitive
public static Connection getConnection(String url,
    String user, String password) throws SQLException {
    java.util.Properties info = new java.util.Properties();

    if (user != null) {
        info.put("user", user);
    }
    if (password != null) {
        info.put("password", password);
    }

    return (getConnection(url, info, Reflection.getCallerClass()));
}

该方法仅仅做了一些赋值操作,最终调的重载方法

private static Connection getConnection(
    String url, java.util.Properties info, Class caller) throws SQLException {
    /*
     * When callerCl is null, we should check the application's
     * (which is invoking this class indirectly)
     * classloader, so that the JDBC driver class outside rt.jar
     * can be loaded from here.
     */
    ClassLoader callerCL = caller != null ? caller.getClassLoader() : null;
    synchronized(DriverManager.class) {
        // synchronize loading of the correct classloader.
        if (callerCL == null) {
            callerCL = Thread.currentThread().getContextClassLoader();
        }
    }

    if(url == null) {
        throw new SQLException("The url cannot be null", "08001");
    }

    println("DriverManager.getConnection(\"" + url + "\")");

    // Walk through the loaded registeredDrivers attempting to make a connection.
    // Remember the first exception that gets raised so we can reraise it.
    SQLException reason = null;

    for(DriverInfo aDriver : registeredDrivers) {
        // If the caller does not have permission to load the driver then
        // skip it.
        if(isDriverAllowed(aDriver.driver, callerCL)) {
            try {
                println("    trying " + aDriver.driver.getClass().getName());
                Connection con = aDriver.driver.connect(url, info);
                if (con != null) {
                    // Success!
                    println("getConnection returning " + aDriver.driver.getClass().getName());
                    return (con);
                }
            } catch (SQLException ex) {
                if (reason == null) {
                    reason = ex;
                }
            }

        } else {
            println("    skipping: " + aDriver.getClass().getName());
        }

    }

    // if we got here nobody could connect.
    if (reason != null)    {
        println("getConnection failed: " + reason);
        throw reason;
    }

    println("getConnection: no suitable driver found for "+ url);
    throw new SQLException("No suitable driver found for "+ url, "08001");
}

该方法中我们可以看到是通过内部成员变量registeredDrivers中获取驱动(Driver)创建的Connection。那registeredDrivers是在什么时候加载的呢?

接着看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");
}

从注释可以看出jdk通过两各方法加载驱动:

  1. 通过系统属性jdbc.properties
  2. 通过ServiceLoader

那么具体是如何实现的呢,继续看loadInitialDrivers()的源码

private static void loadInitialDrivers() {
    String drivers;
    try {
        drivers = AccessController.doPrivileged(new PrivilegedAction() {
            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() {
        public Void run() {

            ServiceLoader loadedDrivers = ServiceLoader.load(Driver.class);
            Iterator 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);
        }
    }
}

可以看到注释和实现有点冲突,实际读取的是jdbc.drivers属性,但这不是重点,因为这两个属性我们都没有配置。所以并不是通过这种方法加载的驱动,那只能是通过另一种方法ServiceLoader来加载驱动类。ServiceLoader是如何加载的呢?这就是今天的主题了,继续看ServiceLoader.load的源码

ServiceLoader.load(Class service) >> ServiceLoader.load(Class service, ClassLoader loader) >> ServiceLoader(Class svc, ClassLoader cl) >> reload() >> new LazyIterator(service, loader)

通过一连串的调用链最终找到目标延迟迭代器(LazyIterator)。最终我们可以看到LazyIterator中加载了一个文件

String fullName = PREFIX + service.getName();
private static final String PREFIX = "META-INF/services/";

service.getName()是我们开始时传入的Driver.class, 最终的文件路径是

META-INF/services/java.sql.Driver

深入探究JDK的SPI机制_第2张图片

我们打开mysql的驱动包可以看到刚好个这样的文件,这并不是单纯胡巧合。

深入探究JDK的SPI机制_第3张图片

该文件中有两个驱动类,默认使用的是第一个。现在我们终于知道JDK是如何加载的mysql驱动类了。

 

总结:SPI的实现机制是由JDK定义接口规范,服务提供者去实现接口并按规范在jar包中的MATE-INF/services目录下配置接口的实现类。JDK就能通过ServiceLoader自动加载接口的实现。最终实现可插拔式编程。

Dubbo和spring boot 通过自己实现的SPI机制,达到可扩展性。

你可能感兴趣的:(java,java,jdk,spi)