Java SPI 机制实现项目框架高扩展性

SPI

即Service Provider Interface

适用于:调用者根据实际使用需要,启用、扩展、或者替换框架的实现策略

使用方法:

假设有三个模块service, api, core

  • 在core中定义了一个接口,代码:
public interface MyService {
    void say();
}
  • 在service模块下
// MyServiceImpl1.java
public class MyServiceImpl1 implements MyService {

    private static final String NAME = "MyServiceImpl1";

    @Override
    public void say() {
        System.out.println("hello, I'm " + NAME);
    }
}
// MyServiceImpl2.java
public class MyServiceImpl2 implements MyService {

    private static final String NAME = "MyServiceImpl2";

    @Override
    public void say() {
        System.out.println("hello, I'm " + NAME);
    }
}
  • api模块下,新建文件src/main/resources/META-INF/services/top.simuhunluo.MyService,文件内容
top.simuhunluo.impl.MyServiceImpl1
top.simuhunluo.impl.MyServiceImpl2

api中写一个类文件,通过spi调用所有的接口实现

public class Main {

    public static void main(String[] args) {
        ServiceLoader<MyService> services = ServiceLoader.load(MyService.class);
        for (MyService service : services) {
            service.say();
        }
    }

}
posted @ 2020-06-19 10:52  须小弥  阅读(376)  评论(0编辑  收藏  举报