接口
@SPI
public interface MyTestRegistry {
/**
* 注冊(cè)服務(wù)
*/
@Adaptive
String register(URL url);
}
兩個(gè)實(shí)現(xiàn)
@Activate(group = {"GROUP_A", "GROUP_B"}, order = 999)
public class EtcdRegistry implements MyTestRegistry {
@Override
public String register(URL url) {
return "Etcd register already! ";
}
}
@Activate(group = {"GROUP_B"})
public class ZookeeperRegistry implements MyTestRegistry {
@Override
public String register(URL url) {
return "Zookeeper register already! ";
}
}
配置
etcd=com..xxx.xxx.xxx.EtcdRegistry
zookeeper=com.xxx.xxx.xxx.ZookeeperRegistry
測(cè)試函數(shù)
public class SpiTest {
public static void main(String[] args) {
URL url = URL.valueOf("test://localhost/test")
.addParameter("my.test.registry", "zookeeper");
MyTestRegistry registry = ExtensionLoader
.getExtensionLoader(MyTestRegistry.class)
.getExtension("etcd");
System.out.println("=================");
System.out.println(registry.register(url));
System.out.println("=================");
registry = ExtensionLoader
.getExtensionLoader(MyTestRegistry.class)
.getAdaptiveExtension();
registry.register(url);
System.out.println(registry.register(url));
System.out.println("=================");
ExtensionLoader
.getExtensionLoader(MyTestRegistry.class)
.getActivateExtension(url, new String[]{}, "GROUP_B")
.forEach(p -> System.out.println(p.register(url)));
System.out.println("=================");
}
}
輸出
=================
Etcd register already!
=================
Zookeeper register already!
=================
Zookeeper register already!
Etcd register already!
=================
總結(jié)
@SPI 標(biāo)注是一個(gè)擴(kuò)展點(diǎn)许溅,各種實(shí)現(xiàn)配置在配置文件里(key是實(shí)現(xiàn)名字温鸽,類似spring里的bean name保屯,value是實(shí)現(xiàn)類)
@Adaptive 是自適應(yīng)注解,根據(jù)使用時(shí)url里的參數(shù)嗤朴,動(dòng)態(tài)尋找實(shí)現(xiàn)類
@Activate 是激活注解配椭,可以激活一串實(shí)現(xiàn),常用于filter
注解參數(shù)說(shuō)明
@SPI 的 value (默認(rèn)使用的extension雹姊,可填配置里的etcd或zookeeper)
@Adaptive 的 value (調(diào)用時(shí)股缸,動(dòng)態(tài)匹配url里key的名字,不填為類的駝峰轉(zhuǎn)換xxx.xx.xx)
@Activate 的 group (把所有實(shí)現(xiàn)吱雏,進(jìn)行分組敦姻,激活時(shí),激活整個(gè)組)
@Activate 的 value (類似@Adaptive的value)
@Activate 的 order (激活時(shí)排序)