Dubbo扩展点注解之@SPI

谁借莪1个温暖的怀抱¢ 2023-06-10 09:26 80阅读 0赞

在Dubbo框架中,@SPI注解都是使用在接口上,它的主要作用是标记这个接口是一个Dubbo SPI扩展点,可以有多个内置或用户定义的实现,运行时通过配置找到具体的实现类。

  1. @Documented
  2. @Retention(RetentionPolicy.RUNTIME)
  3. @Target({ElementType.TYPE})
  4. public @interface SPI {
  5. /**
  6. * default extension name
  7. */
  8. String value() default "";
  9. }

value属性代表接口的默认实现,例如Protocol接口的默认实现是dubbo。

  1. @SPI("dubbo")
  2. public interface Protocol {
  3. ......
  4. }

Dubbo在通过ExtensionLoader.getExtensionLoader(Class type)加载扩展点时,会对传入的class做校验:

  1. private static <T> boolean withExtensionAnnotation(Class<T> type) {
  2. return type.isAnnotationPresent(SPI.class);
  3. }
  4. @SuppressWarnings("unchecked")
  5. public static <T> ExtensionLoader<T> getExtensionLoader(Class<T> type) {
  6. if (type == null) {
  7. throw new IllegalArgumentException("Extension type == null");
  8. }
  9. if (!type.isInterface()) {
  10. throw new IllegalArgumentException("Extension type (" + type + ") is not an interface!");
  11. }
  12. if (!withExtensionAnnotation(type)) {
  13. throw new IllegalArgumentException("Extension type (" + type +
  14. ") is not an extension, because it is NOT annotated with @" + SPI.class.getSimpleName() + "!");
  15. }
  16. ExtensionLoader<T> loader = (ExtensionLoader<T>) EXTENSION_LOADERS.get(type);
  17. if (loader == null) {
  18. EXTENSION_LOADERS.putIfAbsent(type, new ExtensionLoader<T>(type));
  19. loader = (ExtensionLoader<T>) EXTENSION_LOADERS.get(type);
  20. }
  21. return loader;
  22. }

从源码中可以看到,扩展点class必须是接口,且被@SPI注解修饰,这是两个必要条件。

发表评论

表情:
评论列表 (有 0 条评论,80人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Dubbo扩展注解@Adaptive

    @Adaptive称为自适应扩展点注解。 在实际应用场景中,一个扩展接口往往会有多种实现类,因为Dubbo是基于URL驱动,所以在运行时,通过传入URL中的某些参数来动态控制