码迷,mamicode.com
首页 > 其他好文 > 详细

常用技术之SPI ServiceLoader

时间:2021-06-02 11:33:45      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:sas   elements   cto   else   迭代   sele   obj   mod   Fix   

ServiceLoader是jdk对SPI(Service Provider Interface)机制的实现, 让具体业务实现与接口分离,让接口可以自由扩展,是非常常用的技术

常用场景如下:

1. java nio java.nio.channels.spi.SelectorProvider
2. java.nio.charset.spi.CharsetProvider
3. java.nio.file.spi.FileSystemProvider
4. com.fasterxml.jackson.databind.Module
5. java.sql.Driver

源码解析

    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);
    }
    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);
    }
        //查找META-INF/services/+service 的文件,并解析
        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;
        }
        //返回上次解析的到类名,并把类名放进providers变量中缓存
        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
        }
java.util.ServiceLoader#iterator迭代器设计模式,如果查询缓存providers中有数据,直接返回,否则交给LazyIterator查找

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

        };
    }

常用技术之SPI ServiceLoader

标签:sas   elements   cto   else   迭代   sele   obj   mod   Fix   

原文地址:https://www.cnblogs.com/nexusHan/p/14812970.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!