Motan使用SPI机制来实现模块间的访问,基于接口和name来获取实现类,降低了模块间的耦合。

首先来看一下使用方式:

有两个注解

    @Documented
    @Retention(RetentionPolicy.RUNTIME)
    @Target({ElementType.TYPE})
    public @interface Spi {
        Scope scope() default Scope.PROTOTYPE;
    }

    @Documented
    @Retention(RetentionPolicy.RUNTIME)
    @Target({ElementType.TYPE})
    public @interface SpiMeta {
        String name() default "";
    }

  @Spi用来注解接口,@SpiMeta用来注解接口的实现类

@Spi(scope = Scope.SINGLETON)
public interface ConfigHandler {
......

  

@SpiMeta(name = MotanConstants.DEFAULT_VALUE)
public class SimpleConfigHandler implements ConfigHandler {
......

  Motan Spi机制遵循JDK的spi机制,在META-INF/services/下面配置实现类的描述。

文件:META-INF/services/com.weibo.api.motan.config.handler.ConfigHandler

com.weibo.api.motan.config.handler.SimpleConfigHandler

  具体的使用方式是:

ConfigHandler configHandler = ExtensionLoader.getExtensionLoader(ConfigHandler.class).getExtension(MotanConstants.DEFAULT_VALUE);

  根据接口类型获取ExtensionLoader,根据想要的实现的名字获取实现类。这里并没有直接new 实现类,而是根据@SpiMeta上的name来获取实现类。类似于工厂模式,给你一个名字,给我一个实现类对象。而且还可以在@Spi注解中配置对象的创建是否是单例的。

public enum Scope {

    /**
     * 单例模式
     */
    SINGLETON,

    /**
     * 多例模式
     */
    PROTOTYPE
}

  

ExtensionLoader的源码分析

Motan的SPI机制实现分析

 

相关文章:

  • 2021-06-30
  • 2022-01-16
  • 2021-08-22
  • 2021-12-16
  • 2021-04-19
  • 2022-02-02
  • 2022-12-23
  • 2021-07-02
猜你喜欢
  • 2022-01-29
  • 2021-10-22
  • 2022-12-23
  • 2021-10-03
  • 2022-12-23
  • 2021-12-01
  • 2021-06-28
相关资源
相似解决方案