Java spi

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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。