要害词:SPI、ServiceLoader、AutoService、组件化、APT

对于APT(注解处理器),之前写过一篇,运用自界说注解自己完成ButterKnife功用。最近接手的新项目中用了一个新的东西,便是SPI,拿来研讨下。

SPI, service provider interface,运用接口、配置文件和策略形式,完成了解耦、模块化和组件化。

ServiceLoader的运用

  1. 在公共模块或许接口模块中界说一个接口类;
    com.aya.demo.common.ILogInterface.java

    public interface ILogInterface{
        void logD(String msg)
    }
    
  2. 在实践业务模块中,写一个接口的完成类;
    com.aya.demo.LogImpl.java

    public class LogImpl implements ILogInterface{
        @Override
        public void logD(String msg){
            Log.d("AYA", msg);
        }
    }
    
  3. 在该业务模块中,在src/main/resources文件夹下创立/META-INF/services目录,并新建一个文件,文件名是接口的全途径,文件的内容是接口完成类的全途径;
    文件途径如下:
    src/main/resources/META-INF/services/com.aya.demo.common.ILogInterface
    文件内容是:

    com.aya.demo.LogImpl
    
  4. 写一个serverloader东西类。

    SPIUtils.java

     /**
         * 假如有多个完成,取第一个
         */
        public static <T> T getSpiImpl(Class<T> t) {
            try {
                ServiceLoader<T> loader = ServiceLoader.load(t, CommonHolder.ctx.getClassLoader());
                Iterator<T> iter = loader.iterator();
                if (iter.hasNext()) {
                    return iter.next();
                }
            } catch (Exception e) {
                //
            }
            return null;
        }
        /**
         * 回来一切完成
         */
        public static <T> List<T> getSpiImpls(Class<T> t) {
            List<T> impls = new ArrayList<>();
            try {
                ServiceLoader<T> loader = ServiceLoader.load(t, CommonHolder.ctx.getClassLoader());
                Iterator<T> iter = loader.iterator();
                while (iter.hasNext()) {
                    impls.add(iter.next());
                }
            } catch (Exception e) {
                //
            }
            return impls;
        }
    
  5. 运用接口类

    ILogInterface iLog =  SPIUtils.getSpiImpl(ILogInterface.class);
    iLog.d("测验下");
    

运用SPI能够很好的完成解耦合组件化阻隔,但是这样做有一个缺点,便是每次新建一个完成类,就需求在/META-INF/services目录下创立一个文件或许修正已有的文件,不能动态增加,有点费事而且容易写错。针对这种费事的工作,程序员们肯定会想办法处理掉的,所以Google又给我们供给了AutoServcie东西。

AutoService的运用

  1. 首先需求引进依靠

    留意:这个依靠的引进是有讲究的,接口类所在的模块要悉数引进

    // 依靠 autoService 库
    implementation 'com.google.auto.service:auto-service:1.0'
    annotationProcessor 'com.google.auto.service:auto-service:1.0'
    

    而完成类所在的模块只需求引进注解处理器即可:

    // 依靠 autoService 库
    annotationProcessor 'com.google.auto.service:auto-service:1.0'
    

    留意:假如完成类运用的是kotlin编写的,则在引进依靠时需求运用 kapt,即

    apply plugin: 'kotlin-android'
    apply plugin: 'kotlin-kapt'
    dependencies {
        kapt 'com.google.auto.service:auto-service:1.0'
    }
    
  2. 原先的接口类不用动,只需修正完成类
    只需求在具体的完成类上面加上一个@AutoService注解,参数则为接口的class类。

    com.aya.demo.LogImpl.java

    @AutoService(ILogInterface.class)
    public class LogImpl implements ILogInterface{
        @Override
        public void logD(String msg){
            Log.d("AYA", msg);
        }
    }
    
  3. 写一个serverloader东西类SPIUtils.java,同上。

这样,就能够像之前一样运用接口了。

AutoService原理

AutoService的原理便是借助自界说注解,在编译期运用注解处理器扫描注解,并自动生成/resources/META-INF/… 文件。

AutoService东西要害类是 AutoServiceProcessor.java
要害代码如下,加了一些注释:

public class AutoServiceProcessor extends AbstractProcessor {
    ...
    //Multimap:key能够重复
    private final Multimap<String, String> providers = HashMultimap.create();
    ...
      /**
       * <ol>
       *  <li> For each class annotated with {@link AutoService}<ul>
       *      <li> Verify the {@link AutoService} interface value is correct
       *      <li> Categorize the class by its service interface
       *      </ul>
       *
       *  <li> For each {@link AutoService} interface <ul>
       *       <li> Create a file named {@code META-INF/services/<interface>}
       *       <li> For each {@link AutoService} annotated class for this interface <ul>
       *           <li> Create an entry in the file
       *           </ul>
       *       </ul>
       * </ol>
       */
      @Override
      public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
      //该方法数注解处理器的进口
        try {
          processImpl(annotations, roundEnv);
        } catch (RuntimeException e) {
          // We don't allow exceptions of any kind to propagate to the compiler
          fatalError(getStackTraceAsString(e));
        }
        return false;
      }
      private void processImpl(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
        if (roundEnv.processingOver()) {
            //假如现已处理结束,则去生成注册文件
            generateConfigFiles();
        } else {
            //处理注解
            processAnnotations(annotations, roundEnv);
        }
      }
        //处理注解
      private void processAnnotations(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
        //获取一切增加AutoService注解的类
        Set<? extends Element> elements = roundEnv.getElementsAnnotatedWith(AutoService.class);
        log(annotations.toString());
        log(elements.toString());
        for (Element e : elements) {
          // TODO(gak): check for error trees?
          TypeElement providerImplementer = MoreElements.asType(e);
          //获取AutoService注解value,即声明完成类时注解括号里指定的接口
          AnnotationMirror annotationMirror = getAnnotationMirror(e, AutoService.class).get();
          //获取value的调集
          Set<DeclaredType> providerInterfaces = getValueFieldOfClasses(annotationMirror);
          if (providerInterfaces.isEmpty()) {
            //假如调集为空,也便是没有指定value,报错,不处理
            error(MISSING_SERVICES_ERROR, e, annotationMirror);
            continue;
          }
          //遍历一切value,获取value的完整类名
          for (DeclaredType providerInterface : providerInterfaces) {
            TypeElement providerType = MoreTypes.asTypeElement(providerInterface);
            log("provider interface: " + providerType.getQualifiedName());
            log("provider implementer: " + providerImplementer.getQualifiedName());
            //判别是否为接口的完成类,是,则存入Multimap类型的providers缓存中,其间key为接口的全途径,value为完成类的全途径;不然报错
            if (checkImplementer(providerImplementer, providerType, annotationMirror)) {
              providers.put(getBinaryName(providerType), getBinaryName(providerImplementer));
            } else {
              String message = "ServiceProviders must implement their service provider interface. "
                  + providerImplementer.getQualifiedName() + " does not implement "
                  + providerType.getQualifiedName();
              error(message, e, annotationMirror);
            }
          }
        }
      }
        //生成spi文件
      private void generateConfigFiles() {
        Filer filer = processingEnv.getFiler();
        //遍历providers的key值
        for (String providerInterface : providers.keySet()) {
          String resourceFile = "META-INF/services/" + providerInterface;
          log("Working on resource file: " + resourceFile);
          try {
            SortedSet<String> allServices = Sets.newTreeSet();
            try {
              // would like to be able to print the full path
              // before we attempt to get the resource in case the behavior
              // of filer.getResource does change to match the spec, but there's
              // no good way to resolve CLASS_OUTPUT without first getting a resource.
              //"META-INF/services/**"文件夹下现已存在SPI文件
              FileObject existingFile = filer.getResource(StandardLocation.CLASS_OUTPUT, "",
                  resourceFile);
              log("Looking for existing resource file at " + existingFile.toUri());
              // 该SPI文件中的service调集
              Set<String> oldServices = ServicesFiles.readServiceFile(existingFile.openInputStream());
              log("Existing service entries: " + oldServices);
              //将spi文件中的service写入缓存
              allServices.addAll(oldServices);
            } catch (IOException e) {
              // According to the javadoc, Filer.getResource throws an exception
              // if the file doesn't already exist.  In practice this doesn't
              // appear to be the case.  Filer.getResource will happily return a
              // FileObject that refers to a non-existent file but will throw
              // IOException if you try to open an input stream for it.
              log("Resource file did not already exist.");
            }
            //依据providers缓存创立service调集
            Set<String> newServices = new HashSet<>(providers.get(providerInterface));
            //假如新建的都现已存在,则直接回来不处理
            if (allServices.containsAll(newServices)) {
              log("No new service entries being added.");
              return;
            }
            //将新建的service也加入缓存
            allServices.addAll(newServices);
            log("New service file contents: " + allServices);
            //将一切的service写入文件
            FileObject fileObject = filer.createResource(StandardLocation.CLASS_OUTPUT, "",
                resourceFile);
            try (OutputStream out = fileObject.openOutputStream()) {
              ServicesFiles.writeServiceFile(allServices, out);
            }
            log("Wrote to: " + fileObject.toUri());
          } catch (IOException e) {
            fatalError("Unable to create " + resourceFile + ", " + e);
            return;
          }
        }
      }
      ...
}

写SPI的File东西类ServicesFiles.java

final class ServicesFiles {
  public static final String SERVICES_PATH = "META-INF/services";
  private ServicesFiles() { }
    ...
  /**
   * Writes the set of service class names to a service file.
   *
   * @param output not {@code null}. Not closed after use.
   * @param services a not {@code null Collection} of service class names.
   * @throws IOException
   */
  static void writeServiceFile(Collection<String> services, OutputStream output)
      throws IOException {
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(output, UTF_8));
    for (String service : services) {
      writer.write(service);
      writer.newLine();
    }
    writer.flush();
  }
}

看了源码后,能够发现,AutoServiceProcessor的主要功用便是将加了AutoService注解的类写到SPI文件中去,而SPI文件的名称依据注解时value的内容来定的,即接口的全途径,SPI文件的内容是完成类的全途径,每个完成类占一行。

运用AutoService时需求留意:

  1. minSdkVersion最低为26
  2. 接口的完成类必须是public的

总结一下吧,SPI能够更好的完成组件化,结合AUtoService和ServiceLoader来完成,很便利。当然也能够自己开发一个sdk,把SPIUtils放进去,就能够更便利的运用了。

APT的使用,除了ButterKnife、AUtoService,还有阿里的ARouter,都是程序员的智慧结晶!敬服这些大牛。

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。