spi~在插件開發過(guo)程中的使(shi)用
spi是原(yuan)生java的組件(jian),通過(guo)(guo)META-INF/services目錄進(jin)行(xing)注冊,通過(guo)(guo)ServiceLoader進(jin)行(xing)加(jia)載,一般(ban)可以用(yong)(yong)在(zai)組件(jian)開發(fa)中,你在(zai)公用(yong)(yong)組件(jian)中封裝好邏輯,將個(ge)性化的部(bu)分抽象出(chu)一個(ge)接(jie)口(kou),接(jie)口(kou)通過(guo)(guo)spi的方式(shi)進(jin)行(xing)加(jia)載,在(zai)外部(bu)開發(fa)人員引(yin)用(yong)(yong)你的組件(jian)之后,通過(guo)(guo)實(shi)現接(jie)口(kou)來擴展個(ge)性化的功能(neng),再(zai)通過(guo)(guo)META-INF/services對實(shi)現類進(jin)行(xing)注冊。
組件端
先定(ding)義一個公開(kai)的接口
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());
}
在開發人員使用時,需要注冊他的實現類

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

注(zhu)意,在組件內(nei)部讀文(wen)件時(shi),需要采用文(wen)件流的(de)方式(shi),否則(ze),在調用地將出(chu)現無(wu)法(fa)加載的(de)問題(ti)