demo
目录结构
// Cat.java
package spi;
public class Cat implements IShout {
@Override
public void shout() {
System.out.println("miao miao");
}
}
// Dog.java
package spi;
public class Dog implements IShout {
@Override
public void shout() {
System.out.println("wang wang");
}
}
// 接口类
package spi;
public interface IShout {
void shout();
}
// resources/META-INF/services/spi.IShout 文件
spi.Cat
spi.Dog
// 测试
package spi;
import java.util.ServiceLoader;
public class SPIMain {
public static void main(String[] args) {
ServiceLoader<IShout> shouts = ServiceLoader.load(IShout.class);
for (IShout s : shouts) {
s.shout();
}
}
}
// 运行结果
// miao miao
// wang wang
参考
- 高级开发必须理解的Java中SPI机制 - weixin
- SPI(Service Provider Interface)机制与demo:https://www.jianshu.com/p/78df334a40a3