Java SPI机制

概述

  在某些时候我们可以通过在软件上游提供服务接口,无需在意接口的实现逻辑,全部交由扩展程序进行实现,上游只需调用即可,不管扩展程序对接口实现如何更改都不需要对上游程序进行改动。
  Java SPI机制 SPI(Service Provider Interface)是JDK内置的服务发现机制,不同模块间通过接口调用服务,避免对服务接口具体实现类的耦合,如JDBC的数据库驱动。

使用介绍

  • 定义一个接口
  • 项目目录下创建META-INF/services,新建一个名称为上一步定义的接口全限定名的文件,文件内容为定义的接口的实现类全限定名
  • 调用方通过ServiceLoader.load方法加载接口的实现类实例,并通过迭代器获得实例

示例

定义一个支付接口

public interface PayService {
    
    void pay();
    
    void refund();
}

将当前工程生成jar包创建扩展程序并添加依赖


扩展程序实现

扩展程序服务实现

import cn.ruoshy.spi.service.PayService;

public class UserPayService implements PayService {

    @Override
    public void pay() {
        System.out.println("普通用户支付");
    }

    @Override
    public void refund() {
        System.out.println("普通会员退款");
    }

}
import cn.ruoshy.spi.service.PayService;

public class VipPayService implements PayService {

    @Override
    public void pay() {
        System.out.println("Vip用户支付");
    }

    @Override
    public void refund() {
        System.out.println("Vip用户退款");
    }

}

添加接口实现类的全限定名到META-INF/services文件夹下名为接口全限定名的文件中

完成以上步骤后将扩展程序打包成jar包,在服务调用程序中添加依赖

测试
public class Test {

    public static void main(String[] args) {
        ServiceLoader<PayService> serviceLoader = ServiceLoader.load(PayService.class);
        Iterator<PayService> it = serviceLoader.iterator();
        while (it.hasNext()) {
            PayService payService = it.next();
            payService.pay();
            payService.refund();
        }
    }

}

若之后支付逻辑改变,只需要修改扩展程序中的实现类,并添加新的依赖给上游程序,即可实现接口更新

JDBC数据库驱动的实现

mysql在com.mysql.cj.jdbc.Driver类中实现了jdk提供的java.sql.Driver接口

com.mysql.cj.jdbc.Driver

并在项目下创建META-INF/services文件夹新建了以接口全限定名作为文件名的文件

在创建mysql连接的时候一般代码如下:

// MySQL 8.0版本后 com.mysql.jdbc.Driver 更换为 com.mysql.cj.jdbc.Driver
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://xxx.xxx.xxx.xxx/xxx", "xxxx", "xxxxxx");

使用了SPI机制后我们可以不再添加Class.forName代码在使用jdk提供的java.sql.DriverManager类获得连接的时候会调用ensureDriversInitialized()方法,该方法确保了驱动程序是否加载

java.sql.DriverManager类中ensureDriversInitialized()方法:

    /*
     * Load the initial JDBC drivers by checking the System property
     * jdbc.drivers and then use the {@code ServiceLoader} mechanism
     */
    private static void ensureDriversInitialized() {
        // ...略
        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;
            }
        });
        // ...略
    }

通过定义好的接口获得接口实现类,确保驱动程序加载

以上根据mysql实现的功能,我们可以方便的获得数据库连接了,不再需要关注数据库驱动类位置
mysql8.0以下版本使用com.mysql.jdbc.Driver类作为驱动类而8.0后使用com.mysql.cj.jdbc.Driver

public class Test {

    public static void main(String[] args) {
        try {
            Connection conn = DriverManager.getConnection("jdbc:mysql://xxx.xxx.xxx.xxx/xxx", "xxxx", "xxxxxx");
            System.out.println(conn);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 本文以JDBC为例深入讲解 java spi 机制,将帮助你理解:什么是SPI,SPI实现原理,SPI的使用和SP...
    匠丶阅读 5,314评论 0 8
  • 一、Java SPI是什么 SPI的英文全称为Service Provider Interface,字面意思为服务...
    GeekerLou阅读 4,669评论 0 39
  • 主要回顾了java的类加载机制,servlet3.0新特性,java的spi机制,以及spring-mvc的初始化...
    进击de大黄阅读 7,856评论 0 18
  • “我们也不知道怎么就到这儿了。” “快离开这儿,进了村子就再也出不来了。”小姑娘依然紧闭双眼,声音却显得急促。 卢...
    美玲77421阅读 635评论 3 13
  • 一夜冷风吹不尽, 漫卷飞雪舞到今。 冰封天地怎能暖, 屋中火炭却凉心。
    慕容梓月阅读 249评论 0 11

友情链接更多精彩内容