Java spi

作者: wonfi_admin | 来源:发表于2018-03-11 22:13 被阅读0次

    SPI 全称为 (Service Provider Interface) ,是JDK内置的一种服务提供发现机制。 目前有不少框架用它来做服务的扩展发现, 简单来说,它就是一种动态替换发现的机制, 举个例子来说, 有个接口,想运行时动态的给它添加实现,你只需要添加一个实现。

    具体是在JAR包的"src/META-INF/services/"目录下建立一个文件,文件名是接口的全限定名,文件的内容可以有多行,每行都是该接口对应的具体实现类的全限定名。

    先看接口

    package com.demo.service;
    
    public interface Animal {
    
        public void eat();
    }
    

    Animal这个接口有两个实现类

    package com.demo.service.impl;
    
    import com.demo.service.Animal;
    
    public class Cat implements Animal {
    
        public void eat() {
            System.out.println("cat eat");
    
        }
    
    }
    

    package com.demo.service.impl;
    
    import com.demo.service.Animal;
    
    public class Dog implements Animal {
    
        public void eat() {
            System.out.println("dog eat");
    
        }
    
    }
    

    接口写完了,文件的内容如下


    1111.PNG

    运行如下代码,看结果

    package com.demo;
    
    import java.util.ServiceLoader;
    
    import com.demo.service.Animal;
    
    public class Test {
    
        public static void main(String[] args) {
            ServiceLoader<Animal> spi = ServiceLoader.load(Animal.class);
            for(Animal animal : spi){
                animal.eat();
            }
        }
    }
    

    结果是


    1111.PNG

    相关文章

      网友评论

          本文标题:Java spi

          本文链接:https://www.haomeiwen.com/subject/lvcgfftx.html