解耦利器 - Java中的SPI机制

打印 上一主题 下一主题

主题 560|帖子 560|积分 1680

为什么需要SPI机制

SPI和API的区别是什么

SPI是一种跟API相对应的反向设计头脑:API由实现方确定标准规范和功能,调用方无权做任何干预; 而SPI是由调用方确定标准规范,也就是接口,然后调用方依赖此接口,第三方实现此接口,这样做就可以方便的举行扩展,类似于插件机制,这是SPI出现的需求背景。
SPI : “接口”位于“调用方”地点的“包”中

  • 概念上更依赖调用方。
  • 组织上位于调用方地点的包中。
  • 实现位于独立的包中。
  • 常见的例子是:插件模式的插件。
API : “接口”位于“实现方”地点的“包”中

  • 概念上更接近实现方。
  • 组织上位于实现方地点的包中。
  • 实现和接口在一个包中。
什么是SPI机制

SPI(Service Provider Interface),是JDK内置的一种 服务提供发现机制,可以用来启用框架扩展和替换组件,重要是被框架的开辟人员使用,比方数据库中的java.sql.Driver接口,不同的厂商可以针对同一接口做出不同的实现,如下图所示,MySQL和PostgreSQL都有不同的实现提供给用户。
而Java的SPI机制可以为某个接口寻找服务实现,Java中SPI机制重要头脑是将装配的控制权移到程序之外,在模块化设计中这个机制尤其重要,其核心头脑就是 解耦
SPI团体机制图如下:


  • 当服务的提供者提供了一种接口的实现之后,需要在classpath下的 META-INF/services/ 目录里创建一个文件,文件名是以服务接口命名的,而文件里的内容是这个接口的具体的实现类
  • 当其他的程序需要这个服务的时间,就可以通过查找这个jar包(一样寻常都是以jar包做依赖)的META-INF/services/中的设置文件,设置文件中有接口的具体实现类名,再根据这个类名举行加载实例化,就可以使用该服务了。JDK中查找服务的实现的工具类是:java.util.ServiceLoader。
SPI机制的简单示例

假设现在需要一个发送消息的服务MessageService,发送消息的实现可能是基于短信、也可能是基于电子邮件、或推送通知发送消息。

  • 接口界说:首先界说一个接口 MessageService
  1. public interface MessageService {
  2.     void sendMessage(String message);
  3. }
复制代码

  • 提供两个实现类:一个通过短信发送消息,一个通过电子邮件发送消息。
  1. // 短信发送实现
  2. public class SmsMessageService implements MessageService {
  3.     @Override
  4.     public void sendMessage(String message) {
  5.         System.out.println("Sending SMS: " + message);
  6.     }
  7. }
  8. // 电子邮件发送实现
  9. public class EmailMessageService implements MessageService {
  10.     @Override
  11.     public void sendMessage(String message) {
  12.         System.out.println("Sending Email: " + message);
  13.     }
  14. }
复制代码

  • 设置文件:在 META-INF/services/ 目录下创建一个设置文件,文件名为 MessageService ,全限定名 com.example.MessageService,文件内容为接口的实现类的全限定名。
  1. # 文件: META-INF/services/com.seven.MessageService
  2. com.seven.SmsMessageService
  3. com.seven.EmailMessageService
复制代码

  • 加载服务实现:在应用程序中,通过 ServiceLoader 动态加载并使用这些实现类。
  1. public class Application {
  2.     public static void main(String[] args) {
  3.         ServiceLoader<MessageService> loader = ServiceLoader.load(MessageService.class);
  4.         for (MessageService service : loader) {
  5.             service.sendMessage("Hello, SPI!");
  6.         }
  7.     }
  8. }
复制代码
运行时,ServiceLoader 会发现并加载设置文件中列出的所有实现类,并依次调用它们的 sendMessage 方法。
由于在 设置文件 写了两个实现类,因此两个实现类都会实行 sendMessage 方法。
这就是由于ServiceLoader.load(Search.class)在加载某接口时,会去 META-INF/services 下找接口的全限定名文件,再根据里面的内容加载相应的实现类。
这就是spi的头脑,接口的实现由provider实现,provider只用在提交的jar包里的META-INF/services下根据平台界说的接口新建文件,并添加进相应的实现类内容就好。
SPI机制的应用

JDBC DriverManager

在JDBC4.0之前,开辟毗连数据库的时间,通常会用Class.forName("com.mysql.jdbc.Driver")这句先加载数据库相干的驱动,然后再举行获取毗连等的操作。而JDBC4.0之后不需要用Class.forName("com.mysql.jdbc.Driver")来加载驱动,直接获取毗连就可以了,原因就是现在使用了Java的SPI扩展机制来实现。

如上图所示:

  • 首先在java中界说了接口 java.sql.Driver,并没有具体的实现,具体的实现都是由不同厂商来提供的。
  • 在mysql的jar包mysql-connector-java-8.0.26.jar中,可以找到 META-INF/services 目录,该目录下会有一个名字为 java.sql.Driver 的文件,文件内容是com.mysql.cj.jdbc.Driver,这里面的内容就是mysql针对Java中界说的接口的实现。
  • 同样在ojdbc的jar包ojdbc11.jar中,也可以找到同样的设置文件,文件内容是 oracle.jdbc.OracleDriver,这是oracle数据库对Java的java.sql.Driver的实现。
使用方法

而现在Java中写毗连数据库的代码的时间,不需要再使用Class.forName("com.mysql.jdbc.Driver")来加载驱动了,直接获取毗连就可以了:
  1. String url = "jdbc:xxxx://xxxx:xxxx/xxxx";
  2. Connection conn = DriverManager.getConnection(url, username, password);
  3. .....
复制代码
这里并没有涉及到spi的使用,看下面源码。
源码实现

上面的使用方法,就是普通的毗连数据库的代码,实际上并没有涉及到 SPI 的东西,但是有一点可以确定的是,我们没有写有关具体驱动的硬编码Class.forName("com.mysql.jdbc.Driver")!
而上面的代码就可以直接获取数据库毗连举行操作,但是跟SPI有啥关系呢?
既然上面代码没有加载驱动的代码,那实际上是怎么去确定使用哪个数据库毗连的驱动呢?
这里就涉及到使用Java的SPI 扩展机制来查找相干驱动的东西了,关于驱动的查找其实都在DriverManager中,DriverManager是Java中的实现,用来获取数据库毗连,源码如下:
  1. public class DriverManager {
  2.     // 存放注册的jdbc驱动
  3.     private final static CopyOnWriteArrayList<DriverInfo> registeredDrivers = new CopyOnWriteArrayList<>();
  4.     /**
  5.      * Load the initial JDBC drivers by checking the System property
  6.      * jdbc.properties and then use the {@code ServiceLoader} mechanism
  7.      */
  8.     static {
  9.         loadInitialDrivers();
  10.         println("JDBC DriverManager initialized");
  11.     }
  12.    
  13.     private static void loadInitialDrivers() {
  14.         String drivers;
  15.         try {
  16.             // 从JVM -D参数读取jdbc驱动
  17.             drivers = AccessController.doPrivileged(new PrivilegedAction<String>() {
  18.                 public String run() {
  19.                     return System.getProperty("jdbc.drivers");
  20.                 }
  21.             });
  22.         } catch (Exception ex) {
  23.             drivers = null;
  24.         }
  25.         // If the driver is packaged as a Service Provider, load it.
  26.         // Get all the drivers through the classloader
  27.         // exposed as a java.sql.Driver.class service.
  28.         // ServiceLoader.load() replaces the sun.misc.Providers()
  29.         AccessController.doPrivileged(new PrivilegedAction<Void>() {
  30.             public Void run() {
  31.                 ServiceLoader<Driver> loadedDrivers = ServiceLoader.load(Driver.class);
  32.                 Iterator<Driver> driversIterator = loadedDrivers.iterator();
  33.                 /* Load these drivers, so that they can be instantiated.
  34.                  * It may be the case that the driver class may not be there
  35.                  * i.e. there may be a packaged driver with the service class
  36.                  * as implementation of java.sql.Driver but the actual class
  37.                  * may be missing. In that case a java.util.ServiceConfigurationError
  38.                  * will be thrown at runtime by the VM trying to locate
  39.                  * and load the service.
  40.                  *
  41.                  * Adding a try catch block to catch those runtime errors
  42.                  * if driver not available in classpath but it's
  43.                  * packaged as service and that service is there in classpath.
  44.                  */
  45.                 try{
  46.                     // 加载创建所有Driver
  47.                     while(driversIterator.hasNext()) {
  48.                         // 触发Driver的类加载->在静态代码块中创建Driver对象并放到DriverManager
  49.                         driversIterator.next();
  50.                     }
  51.                 } catch(Throwable t) {
  52.                 // Do nothing
  53.                 }
  54.                 return null;
  55.             }
  56.         });
  57.         println("DriverManager.initialize: jdbc.drivers = " + drivers);
  58.         if (drivers == null || drivers.equals("")) {
  59.             return;
  60.         }
  61.         // 解析JVM参数的jdbc驱动
  62.         String[] driversList = drivers.split(":");
  63.         println("number of Drivers:" + driversList.length);
  64.         for (String aDriver : driversList) {
  65.             try {
  66.                 println("DriverManager.Initialize: loading " + aDriver);
  67.                 // initial为ture
  68.                 // 触发Driver的类加载->在静态代码块中创建Driver对象并放到DriverManager
  69.                 Class.forName(aDriver, true,
  70.                         ClassLoader.getSystemClassLoader());
  71.             } catch (Exception ex) {
  72.                 println("DriverManager.Initialize: load failed: " + ex);
  73.             }
  74.         }
  75.     }
  76. }
复制代码
上面的代码重要步骤是:

  • 从系统变量中获取有关驱动的界说。
  • 使用SPI来获取驱动的实现。
  • 遍历使用SPI获取到的具体实现,实例化各个实现类。
  • 根据第一步获取到的驱动列表来实例化具体实现类。


  • 第二步:使用SPI来获取驱动的实现,对应的代码是:
  1. ServiceLoader<Driver> loadedDrivers = ServiceLoader.load(Driver.class);
复制代码
这里封装了接口类型和类加载器,并初始化了一个迭代器。

  • 第三步:遍历获取到的具体实现,实例化各个实现类,对应的代码如下:
  1. //获取迭代器
  2. Iterator<Driver> driversIterator = loadedDrivers.iterator();
  3. //遍历所有的驱动实现
  4. while(driversIterator.hasNext()) {
  5.     driversIterator.next();
  6. }
复制代码
在遍历的时间,首先调用driversIterator.hasNext()方法,这里会搜索classpath下以及jar包中所有的META-INF/services目录下的java.sql.Driver文件,并找到文件中的实现类的名字,此时并没有实例化具体的实现类(ServiceLoader具体的源码实现在下面)。
然后是调用driversIterator.next();方法,此时就会根据驱动名字具体实例化各个实现类了。现在驱动就被找到并实例化了。
Common-Logging

common-logging(也称Jakarta Commons Logging,缩写 JCL)是常用的日志库门面, 使用了SPI的方式来动态加载和设置日志实现。这种机制答应库在运行时找到合适的日志实现,而无需硬编码具体的日志库。
我们看下它是怎么通过SPI解耦的。
首先,日志实例是通过LogFactory的getLog(String)方法创建的:
  1. public static getLog(Class clazz) throws LogConfigurationException {
  2.     return getFactory().getInstance(clazz);
  3. }
复制代码
LogFatory是一个抽象类,它负责加载具体的日志实现,getFactory()方法源码如下:
  1. public static org.apache.commons.logging.LogFactory getFactory() throws LogConfigurationException {
  2.     // Identify the class loader we will be using
  3.     ClassLoader contextClassLoader = getContextClassLoaderInternal();
  4.     if (contextClassLoader == null) {
  5.         // This is an odd enough situation to report about. This
  6.         // output will be a nuisance on JDK1.1, as the system
  7.         // classloader is null in that environment.
  8.         if (isDiagnosticsEnabled()) {
  9.             logDiagnostic("Context classloader is null.");
  10.         }
  11.     }
  12.     // Return any previously registered factory for this class loader
  13.     org.apache.commons.logging.LogFactory factory = getCachedFactory(contextClassLoader);
  14.     if (factory != null) {
  15.         return factory;
  16.     }
  17.     if (isDiagnosticsEnabled()) {
  18.         logDiagnostic(
  19.                 "[LOOKUP] LogFactory implementation requested for the first time for context classloader " +
  20.                         objectId(contextClassLoader));
  21.         logHierarchy("[LOOKUP] ", contextClassLoader);
  22.     }
  23.     // classpath根目录下寻找commons-logging.properties
  24.     Properties props = getConfigurationFile(contextClassLoader, FACTORY_PROPERTIES);
  25.     // Determine whether we will be using the thread context class loader to
  26.     // load logging classes or not by checking the loaded properties file (if any).
  27.     // classpath根目录下commons-logging.properties是否配置use_tccl
  28.     ClassLoader baseClassLoader = contextClassLoader;
  29.     if (props != null) {
  30.         String useTCCLStr = props.getProperty(TCCL_KEY);
  31.         if (useTCCLStr != null) {
  32.             if (Boolean.valueOf(useTCCLStr).booleanValue() == false) {
  33.                 baseClassLoader = thisClassLoader;
  34.             }
  35.         }
  36.     }
  37.     // 这里真正开始决定使用哪个factory
  38.     // 首先,尝试查找vm系统属性org.apache.commons.logging.LogFactory,其是否指定factory
  39.     if (isDiagnosticsEnabled()) {
  40.         logDiagnostic("[LOOKUP] Looking for system property [" + FACTORY_PROPERTY +
  41.                 "] to define the LogFactory subclass to use...");
  42.     }
  43.     try {
  44.         String factoryClass = getSystemProperty(FACTORY_PROPERTY, null);
  45.         if (factoryClass != null) {
  46.             if (isDiagnosticsEnabled()) {
  47.                 logDiagnostic("[LOOKUP] Creating an instance of LogFactory class '" + factoryClass +
  48.                         "' as specified by system property " + FACTORY_PROPERTY);
  49.             }
  50.             factory = newFactory(factoryClass, baseClassLoader, contextClassLoader);
  51.         } else {
  52.             if (isDiagnosticsEnabled()) {
  53.                 logDiagnostic("[LOOKUP] No system property [" + FACTORY_PROPERTY + "] defined.");
  54.             }
  55.         }
  56.     } catch (SecurityException e) {
  57.         if (isDiagnosticsEnabled()) {
  58.             logDiagnostic("[LOOKUP] A security exception occurred while trying to create an" +
  59.                     " instance of the custom factory class" + ": [" + trim(e.getMessage()) +
  60.                     "]. Trying alternative implementations...");
  61.         }
  62.         // ignore
  63.     } catch (RuntimeException e) {
  64.         if (isDiagnosticsEnabled()) {
  65.             logDiagnostic("[LOOKUP] An exception occurred while trying to create an" +
  66.                     " instance of the custom factory class" + ": [" +
  67.                     trim(e.getMessage()) +
  68.                     "] as specified by a system property.");
  69.         }
  70.         throw e;
  71.     }
  72.     // 第二,尝试使用java spi服务发现机制,在META-INF/services下寻找org.apache.commons.logging.LogFactory实现
  73.     if (factory == null) {
  74.         if (isDiagnosticsEnabled()) {
  75.             logDiagnostic("[LOOKUP] Looking for a resource file of name [" + SERVICE_ID +
  76.                     "] to define the LogFactory subclass to use...");
  77.         }
  78.         try {
  79.             // META-INF/services/org.apache.commons.logging.LogFactory, SERVICE_ID
  80.             final InputStream is = getResourceAsStream(contextClassLoader, SERVICE_ID);
  81.             if (is != null) {
  82.                 // This code is needed by EBCDIC and other strange systems.
  83.                 // It's a fix for bugs reported in xerces
  84.                 BufferedReader rd;
  85.                 try {
  86.                     rd = new BufferedReader(new InputStreamReader(is, "UTF-8"));
  87.                 } catch (java.io.UnsupportedEncodingException e) {
  88.                     rd = new BufferedReader(new InputStreamReader(is));
  89.                 }
  90.                 String factoryClassName = rd.readLine();
  91.                 rd.close();
  92.                 if (factoryClassName != null && !"".equals(factoryClassName)) {
  93.                     if (isDiagnosticsEnabled()) {
  94.                         logDiagnostic("[LOOKUP]  Creating an instance of LogFactory class " +
  95.                                 factoryClassName +
  96.                                 " as specified by file '" + SERVICE_ID +
  97.                                 "' which was present in the path of the context classloader.");
  98.                     }
  99.                     factory = newFactory(factoryClassName, baseClassLoader, contextClassLoader);
  100.                 }
  101.             } else {
  102.                 // is == null
  103.                 if (isDiagnosticsEnabled()) {
  104.                     logDiagnostic("[LOOKUP] No resource file with name '" + SERVICE_ID + "' found.");
  105.                 }
  106.             }
  107.         } catch (Exception ex) {
  108.             // note: if the specified LogFactory class wasn't compatible with LogFactory
  109.             // for some reason, a ClassCastException will be caught here, and attempts will
  110.             // continue to find a compatible class.
  111.             if (isDiagnosticsEnabled()) {
  112.                 logDiagnostic(
  113.                         "[LOOKUP] A security exception occurred while trying to create an" +
  114.                                 " instance of the custom factory class" +
  115.                                 ": [" + trim(ex.getMessage()) +
  116.                                 "]. Trying alternative implementations...");
  117.             }
  118.             // ignore
  119.         }
  120.     }
  121.     // 第三,尝试从classpath根目录下的commons-logging.properties中查找org.apache.commons.logging.LogFactory属性指定的factory
  122.     if (factory == null) {
  123.         if (props != null) {
  124.             if (isDiagnosticsEnabled()) {
  125.                 logDiagnostic(
  126.                         "[LOOKUP] Looking in properties file for entry with key '" + FACTORY_PROPERTY +
  127.                                 "' to define the LogFactory subclass to use...");
  128.             }
  129.             String factoryClass = props.getProperty(FACTORY_PROPERTY);
  130.             if (factoryClass != null) {
  131.                 if (isDiagnosticsEnabled()) {
  132.                     logDiagnostic(
  133.                             "[LOOKUP] Properties file specifies LogFactory subclass '" + factoryClass + "'");
  134.                 }
  135.                 factory = newFactory(factoryClass, baseClassLoader, contextClassLoader);
  136.                 // TODO: think about whether we need to handle exceptions from newFactory
  137.             } else {
  138.                 if (isDiagnosticsEnabled()) {
  139.                     logDiagnostic("[LOOKUP] Properties file has no entry specifying LogFactory subclass.");
  140.                 }
  141.             }
  142.         } else {
  143.             if (isDiagnosticsEnabled()) {
  144.                 logDiagnostic("[LOOKUP] No properties file available to determine" + " LogFactory subclass from..");
  145.             }
  146.         }
  147.     }
  148.     // 最后,使用后备factory实现,org.apache.commons.logging.impl.LogFactoryImpl
  149.     if (factory == null) {
  150.         if (isDiagnosticsEnabled()) {
  151.             logDiagnostic(
  152.                     "[LOOKUP] Loading the default LogFactory implementation '" + FACTORY_DEFAULT +
  153.                             "' via the same classloader that loaded this LogFactory" +
  154.                             " class (ie not looking in the context classloader).");
  155.         }
  156.         factory = newFactory(FACTORY_DEFAULT, thisClassLoader, contextClassLoader);
  157.     }
  158.     if (factory != null) {
  159.         cacheFactory(contextClassLoader, factory);
  160.         if (props != null) {
  161.             Enumeration names = props.propertyNames();
  162.             while (names.hasMoreElements()) {
  163.                 String name = (String) names.nextElement();
  164.                 String value = props.getProperty(name);
  165.                 factory.setAttribute(name, value);
  166.             }
  167.         }
  168.     }
  169.     return factory;
  170. }
复制代码
可以看出,抽象类LogFactory加载具体实现的步骤如下:

  • 从vm系统属性org.apache.commons.logging.LogFactory
  • 使用SPI服务发现机制,发现org.apache.commons.logging.LogFactory的实现
  • 查找classpath根目录commons-logging.properties的org.apache.commons.logging.LogFactory属性是否指定factory实现
  • 使用默认factory实现,org.apache.commons.logging.impl.LogFactoryImpl
LogFactory的getLog()方法返回类型是org.apache.commons.logging.Log接口,提供了从trace到fatal方法。可以确定,假如日志实现提供者只要实现该接口,并且使用继承自org.apache.commons.logging.LogFactory的子类创建Log,一定可以构建一个松耦合的日志系统。
Spring中SPI机制

在springboot的自动装配过程中,终极会加载META-INF/spring.factories文件,重要通过以下几个步骤实现:

  • 服务接口界说: Spring 界说了许多服务接口,如 org.springframework.boot.autoconfigure.EnableAutoConfiguration。
  • 服务提供者实现: 各种具体的模块和库会提供这些服务接口的实现,如各种自动设置类。
  • 服务描述文件: 在实现模块的 JAR 包中,会有一个 META-INF/spring.factories 文件,这个文件中列出了该 JAR 包中实现的自动设置类。
  • 服务加载: Spring Boot 在启动时加载 spring.factories 文件,并实例化这些文件中列出的实现类。
Spring Boot 使用 SpringFactoriesLoader 来加载 spring.factories 文件中列出的所有类,并将它们注册到应用上下文中。需要注意的是,其实这里不仅仅是会去ClassPath路径下查找,会扫描所有路径下的Jar包,只不过这个文件只会在Classpath下的jar包中。
  1. public static final String FACTORIES_RESOURCE_LOCATION = "META-INF/spring.factories";
  2. // spring.factories文件的格式为:key=value1,value2,value3
  3. // 从所有的jar包中找到META-INF/spring.factories文件
  4. // 然后从文件中解析出key=factoryClass类名称的所有value值
  5. public static List<String> loadFactoryNames(Class<?> factoryClass, ClassLoader classLoader) {
  6.     String factoryClassName = factoryClass.getName();
  7.     // 取得资源文件的URL
  8.     Enumeration<URL> urls = (classLoader != null ? classLoader.getResources(FACTORIES_RESOURCE_LOCATION) : ClassLoader.getSystemResources(FACTORIES_RESOURCE_LOCATION));
  9.     List<String> result = new ArrayList<String>();
  10.     // 遍历所有的URL
  11.     while (urls.hasMoreElements()) {
  12.         URL url = urls.nextElement();
  13.         // 根据资源文件URL解析properties文件,得到对应的一组@Configuration类
  14.         Properties properties = PropertiesLoaderUtils.loadProperties(new UrlResource(url));
  15.         String factoryClassNames = properties.getProperty(factoryClassName);
  16.         // 组装数据,并返回
  17.         result.addAll(Arrays.asList(StringUtils.commaDelimitedListToStringArray(factoryClassNames)));
  18.     }
  19.     return result;
  20. }
复制代码
通过 SPI 机制和 spring.factories 文件的配合,Spring Boot 实现了模块化和自动设置的能力。开辟者可以通过界说自动设置类并在 spring.factories 文件中声明它们,从而实现模块的独立和松耦合。这种机制不仅简化了设置和启动过程,还提升了应用的可扩展性和维护性。
SPI 机制通常怎么使用

看完上面的几个例子解析,应该都能知道大概的流程了:

  • 界说标准:界说标准,就是界说接口。比如接口java.sql.Driver
  • 具体厂商大概框架开辟者实现:厂商大概框架开辟者开辟具体的实现:
    在META-INF/services目录下界说一个名字为接口全限定名的文件,比如java.sql.Driver文件,文件内容是具体的实现名字,比如me.cxis.sql.MyDriver。写具体的实现me.cxis.sql.MyDriver,都是对接口Driver的实现。
  • 具体使用:引用具体厂商的jar包来实现我们的功能:
  1. ServiceLoader<Driver> loadedDrivers = ServiceLoader.load(Driver.class);//获取迭代器Iterator driversIterator = loadedDrivers.iterator();//遍历while(driversIterator.hasNext()) {    driversIterator.next();    //可以做具体的业务逻辑}
复制代码

  • 使用规范:

SPI机制实现原理

那么问题来了: 怎么样才气加载这些SPI接口的实现类呢,真正的原因是Java的类加载机制! SPI接口属于java rt核心包,只能由启动类加载器BootStrap classLoader加载,而第三方jar包是用户classPath路径下,根据类加载器的可见性原则:启动类加载器无法加载这些jar包,也就是没法向下委托,所以spi必须冲破这种传统的双亲委派机制,通过自界说的类加载器来加载第三方jar包下的spi接口实现类!
JDK中ServiceLoader方法的具体实现:
  1. //ServiceLoader实现了Iterable接口,可以遍历所有的服务实现者
  2. public final class ServiceLoader<S> implements Iterable<S>{
  3.     //查找配置文件的目录
  4.     private static final String PREFIX = "META-INF/services/";
  5.     //表示要被加载的服务的类或接口
  6.     private final Class<S> service;
  7.     //这个ClassLoader用来定位,加载,实例化服务提供者
  8.     private final ClassLoader loader;
  9.     // 访问控制上下文
  10.     private final AccessControlContext acc;
  11.     // 缓存已经被实例化的服务提供者,按照实例化的顺序存储
  12.     private LinkedHashMap<String,S> providers = new LinkedHashMap<>();
  13.     // 迭代器
  14.     private LazyIterator lookupIterator;
  15.     //重新加载,就相当于重新创建ServiceLoader了,用于新的服务提供者安装到正在运行的Java虚拟机中的情况。
  16.     public void reload() {
  17.         //清空缓存中所有已实例化的服务提供者
  18.         providers.clear();
  19.         //新建一个迭代器,该迭代器会从头查找和实例化服务提供者
  20.         lookupIterator = new LazyIterator(service, loader);
  21.     }
  22.     //私有构造器
  23.     //使用指定的类加载器和服务创建服务加载器
  24.     //如果没有指定类加载器,使用系统类加载器,就是应用类加载器。
  25.     private ServiceLoader(Class<S> svc, ClassLoader cl) {
  26.         service = Objects.requireNonNull(svc, "Service interface cannot be null");
  27.         loader = (cl == null) ? ClassLoader.getSystemClassLoader() : cl;
  28.         acc = (System.getSecurityManager() != null) ? AccessController.getContext() : null;
  29.         reload();
  30.     }
  31.     //解析失败处理的方法
  32.     private static void fail(Class<?> service, String msg, Throwable cause)
  33.         throws ServiceConfigurationError
  34.     {
  35.         throw new ServiceConfigurationError(service.getName() + ": " + msg,
  36.                                             cause);
  37.     }
  38.     private static void fail(Class<?> service, String msg)
  39.         throws ServiceConfigurationError
  40.     {
  41.         throw new ServiceConfigurationError(service.getName() + ": " + msg);
  42.     }
  43.     private static void fail(Class<?> service, URL u, int line, String msg)
  44.         throws ServiceConfigurationError
  45.     {
  46.         fail(service, u + ":" + line + ": " + msg);
  47.     }
  48.     //解析服务提供者配置文件中的一行
  49.     //首先去掉注释校验,然后保存
  50.     //返回下一行行号
  51.     //重复的配置项和已经被实例化的配置项不会被保存
  52.     private int parseLine(Class<?> service, URL u, BufferedReader r, int lc, List<String> names)
  53.                 throws IOException, ServiceConfigurationError{
  54.         //读取一行
  55.         String ln = r.readLine();
  56.         if (ln == null) {
  57.             return -1;
  58.         }
  59.         //#号代表注释行
  60.         int ci = ln.indexOf('#');
  61.         if (ci >= 0) ln = ln.substring(0, ci);
  62.         ln = ln.trim();
  63.         int n = ln.length();
  64.         if (n != 0) {
  65.             if ((ln.indexOf(' ') >= 0) || (ln.indexOf('\t') >= 0))
  66.                 fail(service, u, lc, "Illegal configuration-file syntax");
  67.             int cp = ln.codePointAt(0);
  68.             if (!Character.isJavaIdentifierStart(cp))
  69.                 fail(service, u, lc, "Illegal provider-class name: " + ln);
  70.             for (int i = Character.charCount(cp); i < n; i += Character.charCount(cp)) {
  71.                 cp = ln.codePointAt(i);
  72.                 if (!Character.isJavaIdentifierPart(cp) && (cp != '.'))
  73.                     fail(service, u, lc, "Illegal provider-class name: " + ln);
  74.             }
  75.             if (!providers.containsKey(ln) && !names.contains(ln))
  76.                 names.add(ln);
  77.         }
  78.         return lc + 1;
  79.     }
  80.     //解析配置文件,解析指定的url配置文件
  81.     //使用parseLine方法进行解析,未被实例化的服务提供者会被保存到缓存中去
  82.     private Iterator<String> parse(Class<?> service, URL u) throws ServiceConfigurationError{
  83.         InputStream in = null;
  84.         BufferedReader r = null;
  85.         ArrayList<String> names = new ArrayList<>();
  86.         try {
  87.             in = u.openStream();
  88.             r = new BufferedReader(new InputStreamReader(in, "utf-8"));
  89.             int lc = 1;
  90.             while ((lc = parseLine(service, u, r, lc, names)) >= 0);
  91.         }
  92.         return names.iterator();
  93.     }
  94.     //服务提供者查找的迭代器
  95.     private class LazyIterator implements Iterator<S>{
  96.         Class<S> service;//服务提供者接口
  97.         ClassLoader loader;//类加载器
  98.         Enumeration<URL> configs = null;//保存实现类的url
  99.         Iterator<String> pending = null;//保存实现类的全名
  100.         String nextName = null;//迭代器中下一个实现类的全名
  101.         private LazyIterator(Class<S> service, ClassLoader loader) {
  102.             this.service = service;
  103.             this.loader = loader;
  104.         }
  105.         private boolean hasNextService() {
  106.             if (nextName != null) {
  107.                 return true;
  108.             }
  109.             if (configs == null) {
  110.                 try {
  111.                     String fullName = PREFIX + service.getName();
  112.                     if (loader == null)
  113.                         configs = ClassLoader.getSystemResources(fullName);
  114.                     else
  115.                         configs = loader.getResources(fullName);
  116.                 }
  117.             }
  118.             while ((pending == null) || !pending.hasNext()) {
  119.                 if (!configs.hasMoreElements()) {
  120.                     return false;
  121.                 }
  122.                 pending = parse(service, configs.nextElement());
  123.             }
  124.             nextName = pending.next();
  125.             return true;
  126.         }
  127.         private S nextService() {
  128.             if (!hasNextService())
  129.                 throw new NoSuchElementException();
  130.             String cn = nextName;
  131.             nextName = null;
  132.             Class<?> c = null;
  133.             try {
  134.                 c = Class.forName(cn, false, loader);
  135.             }
  136.             if (!service.isAssignableFrom(c)) {
  137.                 fail(service, "Provider " + cn  + " not a subtype");
  138.             }
  139.             try {
  140.                 S p = service.cast(c.newInstance());
  141.                 providers.put(cn, p);
  142.                 return p;
  143.             }
  144.         }
  145.         public boolean hasNext() {
  146.             if (acc == null) {
  147.                 return hasNextService();
  148.             } else {
  149.                 PrivilegedAction<Boolean> action = new PrivilegedAction<Boolean>() {
  150.                     public Boolean run() { return hasNextService(); }
  151.                 };
  152.                 return AccessController.doPrivileged(action, acc);
  153.             }
  154.         }
  155.         public S next() {
  156.             if (acc == null) {
  157.                 return nextService();
  158.             } else {
  159.                 PrivilegedAction<S> action = new PrivilegedAction<S>() {
  160.                     public S run() { return nextService(); }
  161.                 };
  162.                 return AccessController.doPrivileged(action, acc);
  163.             }
  164.         }
  165.         public void remove() {
  166.             throw new UnsupportedOperationException();
  167.         }
  168.     }
  169.     //获取迭代器
  170.     //返回遍历服务提供者的迭代器
  171.     //以懒加载的方式加载可用的服务提供者
  172.     //懒加载的实现是:解析配置文件和实例化服务提供者的工作由迭代器本身完成
  173.     public Iterator<S> iterator() {
  174.         return new Iterator<S>() {
  175.             //按照实例化顺序返回已经缓存的服务提供者实例
  176.             Iterator<Map.Entry<String,S>> knownProviders
  177.                 = providers.entrySet().iterator();
  178.             public boolean hasNext() {
  179.                 if (knownProviders.hasNext())
  180.                     return true;
  181.                 return lookupIterator.hasNext();
  182.             }
  183.             public S next() {
  184.                 if (knownProviders.hasNext())
  185.                     return knownProviders.next().getValue();
  186.                 return lookupIterator.next();
  187.             }
  188.             public void remove() {
  189.                 throw new UnsupportedOperationException();
  190.             }
  191.         };
  192.     }
  193.     //为指定的服务使用指定的类加载器来创建一个ServiceLoader
  194.     public static <S> ServiceLoader<S> load(Class<S> service, ClassLoader loader){
  195.         return new ServiceLoader<>(service, loader);
  196.     }
  197.     //使用线程上下文的类加载器来创建ServiceLoader
  198.     public static <S> ServiceLoader<S> load(Class<S> service) {
  199.         ClassLoader cl = Thread.currentThread().getContextClassLoader();
  200.         return ServiceLoader.load(service, cl);
  201.     }
  202.     //使用扩展类加载器为指定的服务创建ServiceLoader
  203.     //只能找到并加载已经安装到当前Java虚拟机中的服务提供者,应用程序类路径中的服务提供者将被忽略
  204.     public static <S> ServiceLoader<S> loadInstalled(Class<S> service) {
  205.         ClassLoader cl = ClassLoader.getSystemClassLoader();
  206.         ClassLoader prev = null;
  207.         while (cl != null) {
  208.             prev = cl;
  209.             cl = cl.getParent();
  210.         }
  211.         return ServiceLoader.load(service, prev);
  212.     }
  213.     public String toString() {
  214.         return "java.util.ServiceLoader[" + service.getName() + "]";
  215.     }
  216. }
复制代码

  • 首先,ServiceLoader实现了Iterable接口,所以它有迭代器的属性,这里重要都是实现了迭代器的 hasNext 和 next 方法。这里重要都是调用的lookupIterator的相应hasNext和next方法,lookupIterator是懒加载迭代器。
  • 其次,LazyIterator 中的 hasNext 方法,静态变量PREFIX就是”META-INF/services/”目录,这也就是为什么需要在classpath下的META-INF/services/目录里创建一个以服务接口命名的文件。
  • 最后,通过反射方法Class.forName()加载类对象,并用newInstance方法将类实例化,并把实例化后的类缓存到providers对象中,(LinkedHashMap类型)然后返回实例对象。
所以可以看到ServiceLoader不是实例化以后,就去读取设置文件中的具体实现,并举行实例化。而是比及使用迭代器去遍历的时间,才会加载对应的设置文件去解析,调用hasNext方法的时间会去加载设置文件举行解析,调用next方法的时间举行实例化并缓存。
所有的设置文件只会加载一次,服务提供者也只会被实例化一次,重新加载设置文件可使用reload方法。
JDK SPI机制的缺陷

通过上面的解析,可以发现,我们使用SPI机制的缺陷:

  • 获取某个实现类的方式不够灵活,只能通过 Iterator 情势获取,不能根据某个参数来获取对应的实现类。假如不想用某些实现类,大概某些类实例化很耗时,它也被载入并实例化了,这就造成了浪费。
  • 多个并发多线程使用 ServiceLoader 类的实例是不安全的
关于作者

来自一线程序员Seven的探索与实践,持续学习迭代中~
本文已收录于我的个人博客:https://www.seven97.top
公众号:seven97,欢迎关注~

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

吴旭华

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表