Dubbo扩展点注解之@SPI
在Dubbo框架中,@SPI注解都是使用在接口上,它的主要作用是标记这个接口是一个Dubbo SPI扩展点,可以有多个内置或用户定义的实现,运行时通过配置找到具体的实现类。
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
public @interface SPI {
/**
* default extension name
*/
String value() default "";
}
value属性代表接口的默认实现,例如Protocol接口的默认实现是dubbo。
@SPI("dubbo")
public interface Protocol {
......
}
Dubbo在通过ExtensionLoader.getExtensionLoader(Class
private static <T> boolean withExtensionAnnotation(Class<T> type) {
return type.isAnnotationPresent(SPI.class);
}
@SuppressWarnings("unchecked")
public static <T> ExtensionLoader<T> getExtensionLoader(Class<T> type) {
if (type == null) {
throw new IllegalArgumentException("Extension type == null");
}
if (!type.isInterface()) {
throw new IllegalArgumentException("Extension type (" + type + ") is not an interface!");
}
if (!withExtensionAnnotation(type)) {
throw new IllegalArgumentException("Extension type (" + type +
") is not an extension, because it is NOT annotated with @" + SPI.class.getSimpleName() + "!");
}
ExtensionLoader<T> loader = (ExtensionLoader<T>) EXTENSION_LOADERS.get(type);
if (loader == null) {
EXTENSION_LOADERS.putIfAbsent(type, new ExtensionLoader<T>(type));
loader = (ExtensionLoader<T>) EXTENSION_LOADERS.get(type);
}
return loader;
}
从源码中可以看到,扩展点class必须是接口,且被@SPI注解修饰,这是两个必要条件。
还没有评论,来说两句吧...