SPI简介
SPI 全称为 (Service Provider Interface) ,是JDK内置的一种服务提供发现机制。为某一接口实现服务的机制。
适用场景
项目版本升级,不同开发人员负责自己的模块的升级且互不干扰。(公司项目中场景)
案例说明
- 接口定义
package com.upgrade;
public interface UpgradeOperation {
/**
* 执行更新方法
*/
void execute(OperationContext context);
/**
* 版本信息
*/
OSVersionBuild build();
/**
* 执行同一版本更新优先级(从小到大依次执行)
* @return
*/
int priority();
/**
* 唯一标识符
* @return
*/
String getId();
}
- 接口实现
UdsqlUpgradeOperation7_3_1Impl
package com.upgrade.impl;
public class UdsqlUpgradeOperation7_3_1Impl implements UpgradeOperation {
@Override
public void execute(OperationContext context) {
}
@Override
public OSVersionBuild build() {
return OSVersionBuild.VERSION_7_3_1;
}
@Override
public int priority() {
return 0;
}
@Override
public String getId() {
return "7.3.1_udsql";
}
}
UdsqlUpgradeOperation7_3_2Impl
package com.upgrade.impl;
public class UdsqlUpgradeOperation7_3_2Impl implements UpgradeOperation {
@Override
public void execute(OperationContext context) {
}
@Override
public OSVersionBuild build() {
return OSVersionBuild.VERSION_7_3_1;
}
@Override
public int priority() {
return 0;
}
@Override
public String getId() {
return "7.3.2_udsql";
}
}
- 实现SPI需要在META-INF/services中新建以服务接口命名的文件com.upgrade.UpgradeOperation.内容如下:
com.upgrade.impl.UdsqlUpgradeOperation7_3_1Impl
com.upgrade.impl.UdsqlUpgradeOperation7_3_2Impl
- 客户端代码
public static List<UpgradeOperation> getUpgradeOperations() {
List<UpgradeOperation> upgradeOperations = new ArrayList<>();
ServiceLoader<UpgradeOperation> operations = ServiceLoader.load(UpgradeOperation.class);
Iterator<UpgradeOperation> iterator = operations.iterator();
while (iterator.hasNext()) {
UpgradeOperation operation = iterator.next();
upgradeOperations.add(operation);
}
return upgradeOperations;
}
利用SPI机制可以获取目录下所有UpgradeOperation接口的实现。