Java的SPI机制

SPI(Service Provider Interface),是JDK内置的一种 服务提供发现机制.可以为某个接口寻找服务实现.

demo:

vbnet 复制代码
public class TestSpi {

    public static void main(String[] args) throws InstantiationException, IllegalAccessException {
        ServiceLoader<SpiInterface> load = ServiceLoader.load(SpiInterface.class);
        Iterator<SpiInterface> iterator = load.iterator();
        if (iterator.hasNext()) {
            SpiInterface next = iterator.next();
            next.spiInterFaceMethod("hello");
        }
    }
}

接口:

arduino 复制代码
public interface SpiInterface {
    
    public List<String> spiInterFaceMethod(String keyword);
}

SPI实现类:

typescript 复制代码
public class FileSearch implements SpiInterface {
    @Override
    public List<String> spiInterFaceMethod(String keyword) {
        System.out.println("测试SPI机制");
        return null;
    }
}

在resources目录下创建META-INF/services路径.然后再以包路径创建一个文件.

执行结果:

SPI分析:

load方法:

xml 复制代码
    /**
     * Creates a new service loader for the given service type, using the
     * current thread's {@linkplain java.lang.Thread#getContextClassLoader
     * context class loader}.
     *
     * <p> An invocation of this convenience method of the form
     *
     * <blockquote><pre>
     * ServiceLoader.load(<i>service</i>)</pre></blockquote>
     *
     * is equivalent to
     *
     * <blockquote><pre>
     * ServiceLoader.load(<i>service</i>,
     *                    Thread.currentThread().getContextClassLoader())</pre></blockquote>
     *
     * @param  <S> the class of the service type
     *
     * @param  service
     *         The interface or abstract class representing the service
     *
     * @return A new service loader
     */
    public static <S> ServiceLoader<S> load(Class<S> service) {
        ClassLoader cl = Thread.currentThread().getContextClassLoader();
        return ServiceLoader.load(service, cl);
    }

load方法分析:

vbnet 复制代码
    /**
     * Creates a new service loader for the given service type and class
     * loader.
     *
     * @param  <S> the class of the service type
     *
     * @param  service
     *         The interface or abstract class representing the service
     *
     * @param  loader
     *         The class loader to be used to load provider-configuration files
     *         and provider classes, or <tt>null</tt> if the system class
     *         loader (or, failing that, the bootstrap class loader) is to be
     *         used
     *
     * @return A new service loader
     */
    public static <S> ServiceLoader<S> load(Class<S> service,
                                            ClassLoader loader)
    {
        return new ServiceLoader<>(service, loader);
    }

构造了一个ServiceLoader对象.

ini 复制代码
private ServiceLoader(Class<S> svc, ClassLoader cl) {
        service = Objects.requireNonNull(svc, "Service interface cannot be null");
        loader = (cl == null) ? ClassLoader.getSystemClassLoader() : cl;
        acc = (System.getSecurityManager() != null) ? AccessController.getContext() : null;
        reload();
    }

构造方法理解:

reload方法:

csharp 复制代码
    /**
     * Clear this loader's provider cache so that all providers will be
     * reloaded.
     *
     * <p> After invoking this method, subsequent invocations of the {@link
     * #iterator() iterator} method will lazily look up and instantiate
     * providers from scratch, just as is done by a newly-created loader.
     *
     * <p> This method is intended for use in situations in which new providers
     * can be installed into a running Java virtual machine.
     */
    public void reload() {
        providers.clear();
        lookupIterator = new LazyIterator(service, loader);
    }

reload方法就是构造了一个叫做LazyIterator的迭代器对象.

hasNext方法:

typescript 复制代码
public boolean hasNext() {
            if (acc == null) {
                return hasNextService();
            } else {
                PrivilegedAction<Boolean> action = new PrivilegedAction<Boolean>() {
                    public Boolean run() { return hasNextService(); }
                };
                return AccessController.doPrivileged(action, acc);
            }
        }

hasNextService方法:

ini 复制代码
    private boolean hasNextService() {
            if (nextName != null) {
                return true;
            }
            if (configs == null) {
                try {
                    String fullName = PREFIX + service.getName();
                    if (loader == null)
                        configs = ClassLoader.getSystemResources(fullName);
                    else
                        configs = loader.getResources(fullName);
                } catch (IOException x) {
                    fail(service, "Error locating configuration files", x);
                }
            }
            while ((pending == null) || !pending.hasNext()) {
                if (!configs.hasMoreElements()) {
                    return false;
                }
                pending = parse(service, configs.nextElement());
            }
            nextName = pending.next();
            return true;
        }

hasNextService方法理解:

​

next方法:

csharp 复制代码
   public S next() {
            if (acc == null) {
                return nextService();
            } else {
                PrivilegedAction<S> action = new PrivilegedAction<S>() {
                    public S run() { return nextService(); }
                };
                return AccessController.doPrivileged(action, acc);
            }
        }

nextService方法:

typescript 复制代码
  private S nextService() {
            if (!hasNextService())
                throw new NoSuchElementException();
            String cn = nextName;
            nextName = null;
            Class<?> c = null;
            try {
                c = Class.forName(cn, false, loader);
            } 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
        }

nextService方法理解:

这就是SPI机制的一个流程.

类加载器的cast方法:

SPI机制的缺陷:

1.不能按需加载,需要遍历所有的实现,并实例化,然后在循环中才能找到我们需要的实现。如果不想用某些实现类,或者某些类实例化很耗时,它也被载入并实例化了,这就造成了浪费.

2.获取某个实现类的方式不够灵活,只能通过 Iterator 形式获取,不能根据某个参数来获取对应的实现类.

3.多个并发多线程使用 ServiceLoader 类的实例是不安全的.

语雀地址www.yuque.com/itbosunmian...?

《Go.》 密码:xbkk 欢迎大家访问.提意见.

相关推荐
考虑考虑3 小时前
JDK27结构化并发
java·后端·java ee
沐言人生3 小时前
自媒体人的效率神器!监控、采集、下载、发布,这个免费开源工具全拿下!
前端·vue.js·后端
我叫黑大帅5 小时前
拒绝加字段堆屎山!利用位掩码与流程编排优雅落地 上图下文 复合状态
后端·算法·面试
一条Go5 小时前
Grafana 面板嵌入:为什么 kiosk 必须是「裸参数」
后端·github
Cosolar5 小时前
监控指标全正常,订单接口从 80ms 涨到 4s 故障复盘
java·后端·面试
代码丰7 小时前
不依赖 LangGraph,也能实现 Human-in-the-loop:基于数据库状态机的人机协作工作流-CSDN博客
后端·架构
IT_陈寒8 小时前
Java实战技巧总结:当你的finally块没有执行时会发生什么?
前端·人工智能·后端
Csvn8 小时前
Nginx 与 OpenResty:阶段钩子、shared dict 与动态 upstream/证书
后端·nginx
geovindu9 小时前
rust: Functional Options Pattern
开发语言·后端·设计模式·rust·函数式选项模式·惯用法型模式
Java与AI落地9 小时前
RAG 第二步:检索质量不行,先别换模型
后端