美文网首页
Java中的SPI机制

Java中的SPI机制

作者: 曾泽浩 | 来源:发表于2019-11-28 12:22 被阅读0次

    在学习SPI之前,在了解一下API(应用程序接口),API就是服务方定义好接口和实现,然后提供暴露一个接口给调用方。那什么是SPI呢?

    SPI介绍

    SPI ,全称为 Service Provider Interface,是一种服务发现机制。它通过在classpath路径下的META-INF/services文件夹查找文件,自动加载文件里所定义的类。Java自身提供的服务发现机制,是扫描META-INF/services文件夹文件定义的类。但是,也可以自己实现SPI功能,扫描不同的文件夹文件,像DubboSPI机制和SpirngBootSPI机制,都是自己实现的SPI功能,这为很多框架拓展功能提供了更多的可能性。

    SPI可以让开发者拓展JDK自身或者框架本身的功能,就是说开发者是服务实现方,而JDK或者框架是服务调用方。

    简而言之,就是指定那个目录下,通过全限定类名去加载对应的类。

    思考,为什么需要SPI

    思考一个问题,有这样一个需求,需要为某个开源框架或者已有的系统拓展一下功能。

    比较常见的做法可能是在原来的代码进行修改,然后重新编译打包再发布。

    那有没有方法可以不修改原来代码就可以进行拓展呢?答案就是SPI,这要求原来提供框架的开发者,使用SPI,定义接口(interface)或者抽象类(abstract class), 以及实现了服务接口的具体类。

    在使用中,框架提供接口,框架提供基础的实现类,开发者可以去拓展自己的实现类。其中实现类的定义需要放在META-INF/services下面, 在运行时框架会扫描服务配置文件下面的实现类,从而框架就可以调用。

    使用实例

    定义一个接口

    public interface SPIService {
        void service();
    }
    

    原系统调用

    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();
            }
        }
    }
    

    实现类1

    public class SPIServiceA implements SPIService {
        @Override
        public void service() {
            System.out.println("SPIServiceA");
        }
    }
    

    实现类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目录下,所有实现了Driver接口的类,因此在mysql中实现了Driver接口的类会被加载,然后执行静态块,这样子就实现了不同数据库的驱动注册。

    com.mysql.jdbc.Driver

    public class Driver extends NonRegisteringDriver implements java.sql.Driver {
        //
        // Register ourselves with the DriverManager
        // static块,执行这行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()
        }
    }
    

    相关文章

      网友评论

          本文标题:Java中的SPI机制

          本文链接:https://www.haomeiwen.com/subject/qhtbwctx.html