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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章