写了这么长时间的代码,竟然没有用过jdk SPI的ServiceLoader,深表遗憾!
为什么写这个,因为在看Sentinel配置代码的时候,看到了这个,挺好用的。
用法:
在jar包中,resources 中建立 META-INF/services文件夹,文件名作为接口的全限定名
![](https://img-blog.csdnimg.cn/20200716204715869.png)
![](https://img-blog.csdnimg.cn/20200716204601557.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2x1bWFuMTk5MQ==,size_16,color_FFFFFF,t_70)
public static <S> ServiceLoader<S> getServiceLoader(Class<S> clazz) {
if (shouldUseContextClassloader()) {
return ServiceLoader.load(clazz);
} else {
return ServiceLoader.load(clazz, clazz.getClassLoader());
}
}
public static void main(String[] args) {
ServiceLoader<ProcessorSlots> serviceLoader = ServiceLoaderUtil.getServiceLoader(ProcessorSlots.class);
for (ProcessorSlots processorSlots : serviceLoader) {
System.out.println(processorSlots.getClass());
}
}
打印日志:
class com.example.web.util.NodeSelectorSlot
class com.example.web.util.ClusterBuilderSlot