Android模块开发之SPI

Java提供的SPI全名就是Service Provider Interface,下面是一段官方的解释,,其实就是为某个接口寻找服务的机制,有点类似IOC的思想,将装配的控制权移交给ServiceLoader。SPI在平时我们用到的会比较少,但是在Android模块开发中就会比较有用,不同的模块可以基于接口编程,每个模块有不同的实现service provider,然后通过SPI机制自动注册到一个配置文件中,就可以实现在程序运行时扫描加载同一接口的不同service provider。这样模块之间不会基于实现类硬编码,可插拔。

* <p> A <i>service</i> is a well-known set of interfaces and (usually
* abstract) classes.  A <i>service provider</i> is a specific implementation
* of a service.  The classes in a provider typically implement the interfaces
* and subclass the classes defined in the service itself. 

* <p> For the purpose of loading, a service is represented by a single type,
* that is, a single interface or abstract class.  (A concrete class can be
* used, but this is not recommended.)  A provider of a given service contains
* one or more concrete classes that extend this <i>service type</i> with data
* and code specific to the provider. 

说的可能比较抽象,我们还是通过一个栗子来看看SPI在Android中的应用。先看张工程结构图,有四个模块,一个是app主程序模块,有一个接口interface模块,另外两个就是接口的不同实现模块adisplay和bdisplay。

工程结构.png

栗子很简单,就是点击按钮,加载不同模块实现的方法,如下图所示:


栗子.png

1.接口

首先就是模块之间通信接口的实现,我们这里单独抽出一个模块interface,后面接口的不同实现模块可以都依赖同一个接口模块。接口里面就是一个简单的接口:

package com.example;

public interface Display {
    String display();
}

2.模块实现

接下来就是用不同的模块实现接口,首先需要在模块的build.gradle中加入接口的依赖:

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile project(':interface')
}

然后一个简单的实现类实现接口Display。adisplay模块的实现类就是ADisplay。

package com.example;

public class ADispaly implements Display{
    @Override
    public String display() {
        return "This is display in module adisplay";
    }
}

bdisplay模块的实现类就是BDisplay。

package com.example;

public class BDisplay implements Display{
    @Override
    public String display() {
        return "This is display in module bdisplay";
    }
}

接着就是要把这些接口实现类注册到配置文件中,spi的机制就是注册到META-INF/services中。首先在java的同级目录中new一个包目录resources,然后在resources新建一个目录META-INF/services,再新建一个file,file的名称就是接口的全限定名,在我们的栗子中就是:com.example.Display,文件中就是不同实现类的全限定名,不同实现类分别一行。
adisplay模块最后的工程结构下图所示。文件com.example.Display中的内容就是ADispaly实现类的全限定名com.example.ADispaly

模块工程结构.png

bdisplay模块最后的工程结构和上图类似,文件com.example.Display中的内容就是BDisplay实现类的全限定名com.example.BDisplay
模块的实现就是上面这些,接下来看下主程序模块app中有哪些步骤。

3.加载不同服务

当然在主程序模块中也可以有自己的接口实现:

package com.example.juexingzhe.spidemo;

import com.example.Display;

public class DisplayImpl implements Display {
    @Override
    public String display() {
        return "This is display in module app";
    }
}

在配置文件com.example.Display中的内容就是com.example.juexingzhe.spidemo.DisplayImpl
在界面上放置一个按钮,点击按钮会记载所有模块配置文件中的实现类:

mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loadModule();
            }
});

关键的代码其实就是下面三行,通过ServiceLoader来加载接口的不同实现类,然后会得到迭代器,在迭代器中可以拿到不同实现类全限定名,然后通过反射动态加载实例就可以调用display方法了。

ServiceLoader<Display> loader = ServiceLoader.load(Display.class);
mIterator = loader.iterator();
while (mIterator.hasNext()){
      mIterator.next().display();
}

4.源码分析

主要工作都是在ServiceLoader中,这个类在java.util包中。先看下几个重要的成员变量, PREFIX就是配置文件所在的包目录路径;service就是接口名称,在我们这个例子中就是Display;loader就是类加载器,其实最终都是通过反射加载实例;providers就是不同实现类的缓存,key就是实现类的全限定名,value就是实现类的实例;lookupIterator就是内部类LazyIterator的实例。


    private static final String PREFIX = "META-INF/services/";

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

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

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

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

上面提到SPI的三个关键步骤:

ServiceLoader<Display> loader = ServiceLoader.load(Display.class); mIterator = loader.iterator(); while (mIterator.hasNext()){ mIterator.next().display(); }

先看下第一个步骤load:ServiceLoader提供了两个静态的load方法,如果我们没有传入类加载器,ServiceLoader会自动为我们获得一个当前线程的类加载器,最终都是调用构造函数。

public static <S> ServiceLoader<S> load(Class<S> service) {
        ClassLoader cl =Thread.currentThread().getContextClassLoader();
        return ServiceLoader.load(service, cl);
}

public static <S> ServiceLoader<S> load(Class<S> service,ClassLoader loader)
{
        return new ServiceLoader<>(service, loader);
}

在构造函数中工作很简单就是清除实现类的缓存,实例化迭代器。

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

private ServiceLoader(Class<S> svc, ClassLoader cl) {
    service = svc;
    loader = cl;
    reload();
}

private LazyIterator(Class<S> service, ClassLoader loader) {
            this.service = service;
            this.loader = loader;
}

注意了,我们在外面通过ServiceLoader.load(Display.class)并不会去加载service provider,也就是懒加载的设计模式,这也是Java SPI的设计亮点。

那么service provider在什么地方进行加载?我们接着看第二个步骤loader.iterator(),其实就是返回一个迭代器。我们看下官方文档的解释,这个就是懒加载实现的地方,首先会到providers中去查找有没有存在的实例,有就直接返回,没有再到LazyIterator中查找。

 * Lazily loads the available providers of this loader's service.
 *
 * <p> The iterator returned by this method first yields all of the
 * elements of the provider cache, in instantiation order.  It then lazily
 * loads and instantiates any remaining providers, adding each one to the
 * cache in turn.
public Iterator<S> iterator() {
        return new Iterator<S>() {

            Iterator<Map.Entry<String,S>> knownProviders
                = providers.entrySet().iterator();

            public boolean hasNext() {
                if (knownProviders.hasNext())
                    return true;
                return lookupIterator.hasNext();
            }

            public S next() {
                if (knownProviders.hasNext())
                    return knownProviders.next().getValue();
                return lookupIterator.next();
            }

            public void remove() {
                throw new UnsupportedOperationException();
            }

        };
}

我们一开始providers中肯定是没有缓存的实例的,接着会到LazyIterator中查找,去看看LazyIterator,先看下hasNext()方法。

  1. 首先拿到配置文件名fullName,我们这个例子中是com.example.Display
    2.通过类加载器获得所有模块的配置文件Enumeration<URL> configs configs
    3.依次扫描每个配置文件的内容,返回配置文件内容Iterator<String> pending,每个配置文件中可能有多个实现类的全限定名,所以pending也是个迭代器。
public boolean hasNext() {
    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;
}

在上面hasNext()方法中拿到的nextName就是实现类的全限定名,接下来我们去看看具体实例化工作的地方next():

1.首先根据nextName,Class.forName加载拿到具体实现类的class对象
2.Class.newInstance()实例化拿到具体实现类的实例对象
3.将实例对象转换service.cast为接口
4.将实例对象放到缓存中,providers.put(cn, p),key就是实现类的全限定名,value是实例对象。
5.返回实例对象

public S next() {
    if (!hasNext()) {
        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", x);
    }
    if (!service.isAssignableFrom(c)) {
        ClassCastException cce = new ClassCastException(
                service.getCanonicalName() + " is not assignable from " + c.getCanonicalName());
        fail(service,
             "Provider " + cn  + " not a subtype", cce);
    }
    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,
             x);
    }
    throw new Error();          // This cannot happen
}

到这里我们的源码分析之旅就结束了,主要思想其实就是懒加载的思想。

5.总结

通过Java的SPI机制也有一点缺点就是在运行时通过反射加载类实例,这个对性能会有点影响。但是瑕不掩瑜,SPI机制可以实现不同模块之间方便的面向接口编程,拒绝了硬编码的方式,解耦效果很好。用起来也简单,只需要在目录META-INF/services中配置实现类就行。源码中也用来了懒加载的思想,开发中可以借鉴。
文中的栗子也上传网上,有需要的可以参考:https://github.com/juexingzhe/SPIDemo.git
今天的Android模块开发之SPI就到这里了,后面我们还会再有Android模块开发的相关技术介绍,欢迎关注,谢谢!

欢迎关注公众号:JueCode

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,015评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,262评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,727评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,986评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,363评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,610评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,871评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,582评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,297评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,551评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,053评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,385评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,035评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,079评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,841评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,648评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,550评论 2 270

推荐阅读更多精彩内容