Android模块开发之SPI

转载:https://www.jianshu.com/p/deeb39ccdc53

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值