1、原生Java SPI

定义SomeService接口 :

public interface SomeService {
    void doSomething();
}

定义SomeService接口实现类(服务提供者) :

public class SomeServiceProvider implements SomeService{
    @Override
    public void doSomething() {
        System.out.println("Doing something in SomeServiceProvider");
    }
}

META-INF/services/com.cestc.bigdata.spi.SomeService

注意 : com.cestc.bigdata.spi.SomeServiceProvider2不存在

com.cestc.bigdata.spi.SomeServiceProvider2
com.cestc.bigdata.spi.SomeServiceProvider

Main方法

public class Main {

    public static void main(String[] args) {
        ServiceLoader<SomeService> serviceLoader = ServiceLoader.load(SomeService.class);
        Iterator<SomeService> someServiceIterator = serviceLoader.iterator();
        while (someServiceIterator.hasNext()) {
            try {
                SomeService someService = someServiceIterator.next();
                someService.doSomething();
            } catch (Throwable e) {
                System.out.println(e);
            }
        }
    }
}

注意 : 不能使用for来迭代,如果使用for来迭代,发现一个SPI没有实现的就会进行退出,不往下执行。要使用迭代器。这个可以参考 java.sql.DriverManager#loadInitialDrivers

结果如下 :

java.util.ServiceConfigurationError: com.cestc.bigdata.spi.SomeService: Provider com.cestc.bigdata.spi.SomeServiceProvider2 not found
Doing something in SomeServiceProvider

2、google AutoService

@AutoService 是 Google 提供的一个注解,用于简化 Java SPI 的实现。它可以自动为你的服务提供者生成 META-INF/services 文件,而无需手动创建
以下是使用 @AutoService 注解的示例:
首先,确保在项目中引入 auto-service 依赖。在 Maven 中,你可以添加以下依赖项:

<dependency>
  <groupId>com.google.auto.service</groupId>
  <artifactId>auto-service</artifactId>
  <version>1.0.1</version>
</dependency>

示例如下 :

public interface UserService {
    void sayHello(String name);
}

@AutoService(UserService.class)
public class UserServiceProvider implements UserService{
    @Override
    public void sayHello(String name) {
        System.out.println("hello : " + name);
    }
}

public class Main {

    public static void main(String[] args) {
        ServiceLoader<UserService> serviceLoader = ServiceLoader.load(UserService.class);
        Iterator<UserService> userServiceIterator = serviceLoader.iterator();
        while (userServiceIterator.hasNext()) {
            try {
                UserService someService = userServiceIterator.next();
                someService.sayHello("zhangsan");
            } catch (Throwable e) {
                System.out.println(e);
            }
        }
    }
}

结果输出 :
hello : zhangsan

如感兴趣,点赞加关注,谢谢!!!


journey
32 声望20 粉丝