一文搞懂Java/框架中的SPI机制

Posted 漂流小王子日记

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了一文搞懂Java/框架中的SPI机制相关的知识,希望对你有一定的参考价值。

几天前和一位前辈聊起了Spring技术,大佬突然说了SPI,作为一个熟练使用Spring的民工,心中一紧,咱也不敢说不懂,而是在聊完之后赶紧打开了浏览器,开始的学习之路,所以也就有了这篇文章。废话不多说,咱们开始正文。

定义

SPI的英文全称就是Service Provider Interface,看到全称,心里就有了底了,这是一种将服务接口与服务实现分离以达到解耦可拔插以最大提升了程序可扩展性的机制,
这个机制最大的优点就是无须在代码里指定,进而避免了代码污染,实现了模块的可拔插。在JDK、Spring、Dubbo中都有着它的身影,毕竟框架最核心的作用之一就是解耦,下面详细介绍SPI在JDK、Spring、Dubbo中具体的实现;

JDK SPI

JDK提供了一种比较简单SPI实现,其规范具体如下:

  1. 制定统一的规范(接口,比如 java.sql.Driver);
  2. 服务提供商提供这个规范具体的实现,在自己jar包的META-INF/services/目录里创建一个以服务接口命名的文件,内容是实现类的全命名(比如:com.mysql.jdbc.Driver);
  3. 平台引入外部模块的时候,就能通过该jar包META-INF/services/目录下的配置文件找到该规范具体的实现类名,然后装载实例化,完成该模块的注入;

在java中使用spi最常见的场景就是连接数据库时使用,下面从源码层面对java中spi机制进行解析,下面关键代码已经在代码行后进行数字标识,阅读代码时大家可以参考。
DriverManager类:

static {
	//加载初始驱动,跳到方法具体实现
        loadInitialDrivers();  // 1
        println("JDBC DriverManager initialized");
    }
	
private static void loadInitialDrivers() {  //  2
        String drivers;
        try {
            drivers = AccessController.doPrivileged(new PrivilegedAction<String>() {
                public String run() {
                    return System.getProperty("jdbc.drivers");
                }
            });
        } catch (Exception ex) {
            drivers = null;
        }
        // If the driver is packaged as a Service Provider, load it.
        // Get all the drivers through the classloader
        // exposed as a java.sql.Driver.class service.
        // ServiceLoader.load() replaces the sun.misc.Providers()

        AccessController.doPrivileged(new PrivilegedAction<Void>() {
            public Void run() {
		//这一步其实是初始化完成serviceLoader
                ServiceLoader<Driver> loadedDrivers = ServiceLoader.load(Driver.class);  //  3
                //初始化完成,对加载的具体实现类进行遍历加载
		Iterator<Driver> driversIterator = loadedDrivers.iterator();  // 11

                /* Load these drivers, so that they can be instantiated.
                 * It may be the case that the driver class may not be there
                 * i.e. there may be a packaged driver with the service class
                 * as implementation of java.sql.Driver but the actual class
                 * may be missing. In that case a java.util.ServiceConfigurationError
                 * will be thrown at runtime by the VM trying to locate
                 * and load the service.
                 *
                 * Adding a try catch block to catch those runtime errors
                 * if driver not available in classpath but it\'s
                 * packaged as service and that service is there in classpath.
                 */
                try{
		//迭代器后续判断,可以调到13
                    while(driversIterator.hasNext()) {  //   12
                        driversIterator.next();  // 15
                    }
                } catch(Throwable t) {
                // Do nothing
                }
                return null;
            }
        });

        println("DriverManager.initialize: jdbc.drivers = " + drivers);

        if (drivers == null || drivers.equals("")) {
            return;
        }
        String[] driversList = drivers.split(":");
        println("number of Drivers:" + driversList.length);
        for (String aDriver : driversList) {
            try {
                println("DriverManager.Initialize: loading " + aDriver);
                Class.forName(aDriver, true,
                        ClassLoader.getSystemClassLoader());
            } catch (Exception ex) {
                println("DriverManager.Initialize: load failed: " + ex);
            }
        }
    }

ServiceLoader类

//根据服务类型初始化serviceloader
    public static <S> ServiceLoader<S> load(Class<S> service) {   //4
        ClassLoader cl = Thread.currentThread().getContextClassLoader();
        return ServiceLoader.load(service, cl);
    }
	
	public static <S> ServiceLoader<S> load(Class<S> service,
                                            ClassLoader loader)  // 5
    {
        return new ServiceLoader<>(service, loader);    //6
    }
	// 构造器私有,每次new新对象,但进行lazy load
	private ServiceLoader(Class<S> svc, ClassLoader cl) {  //  7
        service = Objects.requireNonNull(svc, "Service interface cannot be null");
        loader = (cl == null) ? ClassLoader.getSystemClassLoader() : cl;
        acc = (System.getSecurityManager() != null) ? AccessController.getContext() : null;
        reload();  // 8
    }
	
	public void reload() {
        providers.clear();
        lookupIterator = new LazyIterator(service, loader);  // 9
    }
	// ServiceLoader类中的内部类LazyIterator
	private LazyIterator(Class<S> service, ClassLoader loader) {  // 10
            this.service = service;
            this.loader = loader;
    }
	//固定路径前缀META-INF/services下的文件
	private boolean hasNextService() {  // 14
            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;
        }
	//使用class.forname进行类的加载初始化
        private S nextService() {   // 18
            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
        }

        public boolean hasNext() {
            if (acc == null) {
                return hasNextService();  //  13
            } else {
                PrivilegedAction<Boolean> action = new PrivilegedAction<Boolean>() {
                    public Boolean run() { return hasNextService(); }
                };
                return AccessController.doPrivileged(action, acc);
            }
        }

        public S next() {   // 16
            if (acc == null) {
                return nextService();   // 17
            } else {
                PrivilegedAction<S> action = new PrivilegedAction<S>() {
                    public S run() { return nextService(); }
                };
                return AccessController.doPrivileged(action, acc);
            }
        }

以上就是整个java spi的实现,只是简单地的进行扫描加载,并没有实现按需加载。

以上是关于一文搞懂Java/框架中的SPI机制的主要内容,如果未能解决你的问题,请参考以下文章

一文搞懂SPI通信协议

一文搞懂SPI通信协议

一文搞懂SPI通信协议

一文彻底搞懂python的垃圾回收机制及常量池验证

一文搞懂JavaScript垃圾回收机制

一文搞懂JavaScript垃圾回收机制