ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

SPI实现原理介绍

2019-09-22 11:35:47  阅读:270  来源: 互联网

标签:cn service 介绍 loader SPI private 原理 null ServiceLoader


SPI实现原理介绍

SericeLoader

JAVA中的SPI实践学习中了解到查找实现的一个重要方法为:

ServiceLoader shouts = ServiceLoader.load(Handler.class);
其类结构为:

public final class ServiceLoader<S>
    implements Iterable<S>
{
	//SPI配置文件所有路径
    private static final String PREFIX = "META-INF/services/";

    // The class or interface representing the service being loaded
    private final Class<S> service;

    // The class loader used to locate, load, and instantiate providers
    private final ClassLoader loader;

    // The access control context taken when the ServiceLoader is created
    private final AccessControlContext acc;

    // Cached providers, in instantiation order
    private LinkedHashMap<String,S> providers = new LinkedHashMap<>();

    // The current lazy-lookup iterator
    private LazyIterator lookupIterator;

Load方法

是直接实例化了一个ServiceLoader,参考:

return new ServiceLoader<>(service, loader);

在ServiceLoader的构造函数中,

    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

    public void reload() {
        providers.clear();
        lookupIterator = new LazyIterator(service, loader);
    }

查找实现类

查找实现类和创建实现类的过程,都在LazyIterator完成。当我们调用iterator.hasNext和iterator.next方法的时候,实际上调用的都是LazyIterator的相应方法。

List handlers = Lists.newArrayList(shouts.iterator());
ServiceLoader shouts = ServiceLoader.load(Animal.class);
for (Animal s : shouts) {

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

创建实例

调用next方法的时候,实际调用到的是,lookupIterator.nextService。它通过反射的方式,创建实现类的实例并返回。

        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
        }

next---->nextService----->hasNextService---->class.forName

标签:cn,service,介绍,loader,SPI,private,原理,null,ServiceLoader
来源: https://blog.csdn.net/sunquan291/article/details/101150277

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有