Java SPI简介、示例及实现源码分析

一、什么是SPI

SPI(Service Provider Interface)是JDK内置的一种服务发现机制,简单说它就是一种动态归还发现的机制,比如一个接口,想运行时动态给它添加实现,只需要添加一个实现,然后在jar包src/resources/META-INF/service目录下创建一个接口全限定名的文件,文件中存放实现类的全限定名,允许存多个实现类全限定名

二、SPI使用示例
  • 2.1 普通方式-手动写资源文件

定义接口

package com.xiaofan.boot.spi;
public interface AnimalService {
    void eat();
}

定义接口实现类1:

package com.xiaofan.boot.spi.impl;
import com.xiaofan.boot.spi.AnimalService;
public class CatService implements AnimalService {
    @Override
    public void eat() {
        System.out.println("cat eat food!");
    }
}

定义接口实现类2:

package com.xiaofan.boot.spi.impl;
import com.xiaofan.boot.spi.AnimalService;
public class DogService implements AnimalService {
    @Override
    public void eat() {
        System.out.println("dog eat food!");
    }
}

src/resources/文件夹下定义META-INF/services资源文件夹,并定义AnimalService的全限定名资源文件:com.xiaofan.boot.spi.AnimalService

com.xiaofan.boot.spi.impl.CatService
com.xiaofan.boot.spi.impl.DogService

测试:

public class TestSpi {                                                                  
    public static void main(String[] args) {                                            
        ServiceLoader<AnimalService> services = ServiceLoader.load(AnimalService.class);
        Iterator<AnimalService> iterator = services.iterator();                         
        while(iterator.hasNext()) {                                                     
            AnimalService animalService = iterator.next();                              
            animalService.eat();                                                        
        }                                                                               
    }                                                                                   
}    

---
cat eat food!
dog eat food!                                                                                   
  • 2.2 通过注解生成资源文件

通过ServiceLoader可以比较方便地发现META-INF/services下的实现类,但每次都要手动添加文件,比较繁琐。AutoService可以通过注解的方式自动生成资源文件

添加AutoService依赖包,注意升级下guava包版本,否则可能会遇到包冲突问题:

<dependency>
	<groupId>com.google.auto.service</groupId>
	<artifactId>auto-service</artifactId>
	<version>1.0-rc5</version>
	<optional>true</optional>
</dependency>

在接口实现类上添加@AutoService注解

@AutoService(AnimalService.class)
public class CatService implements AnimalService {
    @Override
    public void eat() {
        System.out.println("cat eat food!");
    }
}

测试:

public class TestSpi {
    public static void main(String[] args) {
        ServiceLoader<AnimalService> services = ServiceLoader.load(AnimalService.class);
        Iterator<AnimalService> iterator = services.iterator();
        while(iterator.hasNext()) {
            AnimalService animalService = iterator.next();
            animalService.eat();
        }
    }
}

---
cat eat food!

查看target文件夹结构,AutoService自动生成了META-INFO/services文件夹及AnimalService的全限定名文件:

# jerry @ MacBook-Pro-6 in ~/Documents/git/test/xiaofan-boot/target on git:master x [12:31:53]
$ tree
.
|____classes
| |____com
| | |____xiaofan
| | | |____boot
| | | | |____spi
| | | | | |____AnimalService.class
| | | | | |____impl
| | | | | | |____CatService.class
| | | | | | |____DogService.class
| | | | | |____TestSpi.class
| |____log4j.properties
| |____META-INF
| | |____services
| | | |____com.xiaofan.boot.spi.AnimalService
|____generated-sources
| |____annotations
三、ServiceLoader源码解析

首先看下ServiceLoader的成员变量,ServiceLoader通过PREFIX指定了默认资源文件路径为:META-INF/services/;service为spi指定的接口;loader为加载实现类的ClassLoader;provider为缓存的实现类全限定名与其实例的KV对,所有实现类第一次通过反射生成实例后存储在provider中,供后续使用。

public final class ServiceLoader<S> implements Iterable<S>
{
    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;
...
}

ServiceLoader的load方法主要作用是初始化ServiceLoader的成员变量:service、loader、acc和懒加载迭代器。

    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();
    }
    
    public void reload() {
        providers.clear();
        lookupIterator = new LazyIterator(service, loader);
    }    

ServiceLoader实现了迭代器接口,其迭代器逻辑主要如下,其主要方法hasNext()、next()都是通过懒加载迭代器lookupIterator实现。

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

        };
    }

hasNext()方法核心逻辑如下,初始状态下nextName和configs都为null,程序到/META-INF/services资源文件夹下找与服务同名的资源文件,并加载其配置,将资源文件中的第一个实现类全限定名赋值给nextName

        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()方法核心逻辑如下,通过反射动态生成nextName指定的实现类的对象,将其转换成泛型指定的返回类型,然后将实现类全限定名和其实例以KV形式存储到provider中。

        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
        }
参考
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值