Motan的SPI机制实现分析

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的源码分析

 

posted @ 2017-04-04 13:07  huangll99  阅读(938)  评论(0编辑  收藏  举报