Java SPI的简单小实例

 更新时间:2020年07月13日 09:59:54   作者:不想下火车的人  
这篇文章主要介绍了Java SPI的简单小实例,文中讲解非常细致,代码帮助大家更好的理解和学习,感兴趣的朋友可以了解下

  JDK有个ServiceLoader类,在java.util包里,支持按约定目录/META-INF/services去找到接口全路径命名的文件,读取文件内容得到接口实现类的全路径,加载并实例化。如果我们在自己的代码中定义一个接口,别人按接口实现并打包好了,那么我们只需要引入jar包,通过ServiceLoader就能够把别人的实现用起来。举个例子,JDK中的JDBC提供一个数据库连接驱动接口,不同的厂商可以有不同的实现,如果它们给的jar包里按规定提供了配置和实现类,那么我们就可以执行不同的数据库连接操作,比如MySql的jar包里就会有自己的配置:

  这里文件名就是接口:

   文件内容是实现类:

  我们自己实现一个简单例子,不需要打jar包,把目录放到spring boot的resources下即可,这里就是classpath,跟你放jar包里效果一样。

  1、定义一个接口:

package com.wlf.service;

public interface ITest {
  void saySomething();
}

  2、定义两个实现:

package com.wlf.service.impl;

import com.wlf.service.ITest;

public class ITestImpl1 implements ITest {
  @Override
  public void saySomething() {
    System.out.println("Hi, mia.");
  }
}
package com.wlf.service.impl;

import com.wlf.service.ITest;

public class ITestImpl2 implements ITest {
  @Override
  public void saySomething() {
    System.out.println("Hello, world.");
  }
}

  3、按预定新增/META-INF/services/com.wlf.service.ITest文件:

com.wlf.service.impl.ITestImpl1
com.wlf.service.impl.ITestImpl2

  4、定义一个执行类,通过ServiceLoader加载并实例化,调用实现类方法,跑一下:

package com.wlf.service;

import java.util.Iterator;
import java.util.ServiceLoader;

public class TestServiceLoader {
  public static void main(String[] args) {
    ServiceLoader<ITest> serviceLoader = ServiceLoader.load(ITest.class);
    Iterator<ITest> iTests = serviceLoader.iterator();
    while (iTests.hasNext()) {
      ITest iTest = iTests.next();
      System.out.printf("loading %s\n", iTest.getClass().getName());
      iTest.saySomething();
    }
  }
}

  打印结果:

  ServiceLoader源码比较简单,可以看下上面我们使用到的标黄了的方法:

/**
   * 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.
   *
   * <p> To achieve laziness the actual work of parsing the available
   * provider-configuration files and instantiating providers must be done by
   * the iterator itself. Its {@link java.util.Iterator#hasNext hasNext} and
   * {@link java.util.Iterator#next next} methods can therefore throw a
   * {@link ServiceConfigurationError} if a provider-configuration file
   * violates the specified format, or if it names a provider class that
   * cannot be found and instantiated, or if the result of instantiating the
   * class is not assignable to the service type, or if any other kind of
   * exception or error is thrown as the next provider is located and
   * instantiated. To write robust code it is only necessary to catch {@link
   * ServiceConfigurationError} when using a service iterator.
   *
   * <p> If such an error is thrown then subsequent invocations of the
   * iterator will make a best effort to locate and instantiate the next
   * available provider, but in general such recovery cannot be guaranteed.
   *
   * <blockquote style="font-size: smaller; line-height: 1.2"><span
   * style="padding-right: 1em; font-weight: bold">Design Note</span>
   * Throwing an error in these cases may seem extreme. The rationale for
   * this behavior is that a malformed provider-configuration file, like a
   * malformed class file, indicates a serious problem with the way the Java
   * virtual machine is configured or is being used. As such it is
   * preferable to throw an error rather than try to recover or, even worse,
   * fail silently.</blockquote>
   *
   * <p> The iterator returned by this method does not support removal.
   * Invoking its {@link java.util.Iterator#remove() remove} method will
   * cause an {@link UnsupportedOperationException} to be thrown.
   *
   * @implNote When adding providers to the cache, the {@link #iterator
   * Iterator} processes resources in the order that the {@link
   * java.lang.ClassLoader#getResources(java.lang.String)
   * ClassLoader.getResources(String)} method finds the service configuration
   * files.
   *
   * @return An iterator that lazily loads providers for this loader's
   *     service
   */
  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();
      }

    };
  }

  我们用到的迭代器其实是一个Map:

  // Cached providers, in instantiation order
  private LinkedHashMap<String,S> providers = new LinkedHashMap<>();

  它用来缓存加载的实现类,真正执行的是lookupIterator:

  // The current lazy-lookup iterator
  private LazyIterator lookupIterator;

  我们看下它的hasNext和next方法:

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

    public S next() {
      if (acc == null) {
        return nextService();
      } else {
        PrivilegedAction<S> action = new PrivilegedAction<S>() {
          public S run() { return nextService(); }
        };
        return AccessController.doPrivileged(action, acc);
      }
    }
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;
    }

    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
    }

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

  hasNext查找实现类,并指定了类路径:

private static final String PREFIX = "META-INF/services/";

  具体查找操作看这里:

pending = parse(service, configs.nextElement());

  next则是实例化加载到的实现类,使用反射Class.forName加载类、newInstance实例化对象。

以上就是Java SPI的简单小实例的详细内容,更多关于Java SPI实例的资料请关注脚本之家其它相关文章!

相关文章

  • Java实现BP神经网络MNIST手写数字识别的示例详解

    Java实现BP神经网络MNIST手写数字识别的示例详解

    这篇文章主要为大家详细介绍了Java实现BP神经网络MNIST手写数字识别的相关方法,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起了解一下
    2023-01-01
  • springboot启动不了也不报错的问题及解决

    springboot启动不了也不报错的问题及解决

    这篇文章主要介绍了springboot启动不了也不报错的问题及解决方案,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-05-05
  • IDEA编译乱码Build Output提示信息乱码

    IDEA编译乱码Build Output提示信息乱码

    IDEA编译的时候乱码,Build Output提示信息乱码,本文就详细的介绍一下解决方法,有需要的同学可以了解一下
    2021-06-06
  • Servlet中/和/*的区别详解

    Servlet中/和/*的区别详解

    本文将分析/和/*的区别这个老生常谈的问题,但是很多时候看完就忘了,关于此问题这一篇文章就够了,它将成为你的永久记忆,感兴趣的可以了解一下
    2021-07-07
  • java TreeUtil菜单递归工具类

    java TreeUtil菜单递归工具类

    这篇文章主要为大家详细介绍了java TreeUtil菜单递归工具类,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2020-08-08
  • 详解MyBatis直接执行SQL查询及数据批量插入

    详解MyBatis直接执行SQL查询及数据批量插入

    这篇文章主要介绍了MyBatis直接执行SQL查询及数据批量插入的相关知识,需要的朋友一起学习吧
    2016-01-01
  • spring-cloud入门之eureka-server(服务发现)

    spring-cloud入门之eureka-server(服务发现)

    本篇文章主要介绍了spring-cloud入门之eureka-server(服务发现),小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-01-01
  • Java责任链设计模式

    Java责任链设计模式

    这篇文章主要介绍了Java责任链设计模式的相关资料,需要的朋友可以参考下
    2016-03-03
  • 详解Spring Boot实战之Filter实现使用JWT进行接口认证

    详解Spring Boot实战之Filter实现使用JWT进行接口认证

    本篇文章主要介绍了详解Spring Boot实战之Filter实现使用JWT进行接口认证,具有一定的参考价值,有兴趣的可以了解一下
    2017-07-07
  • Java 泛型(Generic)简介及用法详解

    Java 泛型(Generic)简介及用法详解

    泛型是一种把类型明确的工作推迟到创建对象或者调用方法的时候才去明确的特殊的类型,参数化类型,把类型当作参数一样的传递,本文给大家介绍Java 泛型(Generic)概述及使用,感兴趣的朋友跟随小编一起看看吧
    2023-10-10

最新评论