spi~在插件開發(fā)過程中的使用
spi是原生java的組件,通過META-INF/services目錄進行注冊,通過ServiceLoader進行加載,一般可以用在組件開發(fā)中,你在公用組件中封裝好邏輯,將個性化的部分抽象出一個接口,接口通過spi的方式進行加載,在外部開發(fā)人員引用你的組件之后,通過實現(xiàn)接口來擴展個性化的功能,再通過META-INF/services對實現(xiàn)類進行注冊。
組件端
先定義一個公開的接口
public interface SpiHello {
void printHello();
}
一個公開的組件
public static void print() {
InputStream resource = Tool.class.getClassLoader().getResourceAsStream("licence.txt");
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int bufSize = 1024;
byte[] buffer = new byte[bufSize];
int len = 0;
while (true) {
try {
if (!(-1 != (len = resource.read(buffer, 0, bufSize))))
break;
}
catch (IOException e) {
throw new RuntimeException(e);
}
bos.write(buffer, 0, len);
}
ServiceLoader<SpiHello> spiHellos = ServiceLoader.load(SpiHello.class);
Iterator<SpiHello> iterable = spiHellos.iterator();
while (iterable.hasNext()) {
iterable.next().printHello();
}
System.out.println("value=" + bos.toString());
}
在開發(fā)人員使用時,需要注冊他的實現(xiàn)類

com.lind.pk.Tool.print();
結(jié)果

注意,在組件內(nèi)部讀文件時,需要采用文件流的方式,否則,在調(diào)用地將出現(xiàn)無法加載的問題
浙公網(wǎng)安備 33010602011771號