Service Provider Interfaces 服务提供发现,动态替换发现的机制
示例:
一个接口:
public interface Calc {Logger logger = LoggerFactory.getLogger(Calc.class);
Object calc(int calcType);
}
两个实现:
计算sin值:
public class SinCalc implements Calc {@Overridepublic Object calc(int calcType) {Object value = Math.sin(calcType);logger.info("sin result: {}", value);
return value;
}}
计算开方:
public class SqrtCalc implements Calc {@Overridepublic Object calc(int calcType) {Object value = Math.sqrt(calcType);logger.info("sqrt result: {}", value);
return value;
}}
一个服务加载类:
@Componentpublic class SpiService {public Object execCalc(int value){ServiceLoader<Calc> loader = ServiceLoader.load(Calc.class);
Iterator<Calc> iterator = loader.iterator();while (iterator.hasNext()) {
return iterator.next().calc(value);
}return null;}public static void main(String[] args) {new SpiService().execCalc(100);
}}
一个配置文件:classpath:META-INF/services/xxx.xxx.Calc
内容:需要加载的功能类
如:xxx.xxx.SqrtCalc
则 运行服务加载类执行,输出计算开方。
示例应用项目:https://github.com/windwant/spring-boot-test
官方文档:https://docs.oracle.com/javase/tutorial/sound/SPI-intro.html