美文网首页
SPI实现接口多实现路由

SPI实现接口多实现路由

作者: 瑜骐 | 来源:发表于2018-09-19 18:49 被阅读0次

    SPI简介

    SPI是Service Provider Interfaces的简称。根据Java的SPI规范,我们可以定义一个服务接口,具体的实现由对应的实现者去提供,即Service Provider(服务提供者)。然后在使用的时候只要根据SPI的规范去获取对应的服务提供者的服务实现即可。详细的例子参考:https://www.baeldung.com/java-spi

    ServiceLoader<ExchangeRateProvider> loader = ServiceLoader .load(ExchangeRateProvider.class);
    

    接口多实现路由

    接口多实现路由,其实就是多态,只是和多态有点差别就是其能够自己定义路由规则, 工厂方法

    对于上图的主要问题就是AHandler和BHandler是如何注入到ABFactory中的???,常见的方法有:

    主动注入---接口实现者自己主动注入

    具体各个接口实现自己注入到工厂

    由接口实现者AHandler和BHandler自己将自己注入到工厂ABFactory中,这种实现方式不是很好,因为将接口的实现和工厂强耦合在一起了,不利于分离。

    被动注入---工厂类将接口的实现者注入到工厂中

    工厂类自动扫描注入

    在这种情况下,是由工厂类来扫描或者读取其他配置文件来实现对应的同一个接口不同实现映射的路由,目前主要有两种方式,一种是使用spring,另一种是使用SPI机制

    被动注入--spring

    被动注入-spring

    主要是利用spring bean管理机制来实现的,通过spring 扫描对应的接口实现来将不同的实现注入到工厂中

    被动注入--配置文件

    被动注入-配置文件

    从配置文件中读取对应的配置,来将对应的接口不同实现注入到工厂,如下文件所示:

    参见:https://github.com/alipay/rdf-file
    文件:com.alipay.rdf.file.spi.RdfFileReaderSpi
    protocol=com.alipay.rdf.file.common.ProtocolFileReader
    protocol_multiFile=com.alipay.rdf.file.common.ProtocolFilesSortedReader
    raw=com.alipay.rdf.file.common.RawFileReader
    

    其中SPI的方式也属于这类,SPI通过制定文件名(接口的全限定接口名),文件内容为:

    参见:https://github.com/lwjaiyjk/StudyExample
    文件名:com.yjk.example.spi.DemoService
    #English implementation
    com.yjk.example.spi.impl.EnglishDemoServiceImpl
    #Chinese implementation
    com.yjk.example.spi.impl.ChineseDemoServiceImpl
    
    public class SpiMainTest {
        public static void main(String[] args) {
            ServiceLoader<DemoService> serviceLoader = ServiceLoader.load(DemoService.class);
            Iterator<DemoService> it = serviceLoader.iterator();
            while (it!=null && it.hasNext()) {
                DemoService demoService = it.next();
                System.out.println("class:"+demoService.getClass().getName()+"***"+demoService.sayHi("World"));
            }
        }
    }
    

    参考

    1. https://github.com/lwjaiyjk/StudyExample
    2. https://www.baeldung.com/java-spi
    3. https://github.com/alipay/rdf-file

    相关文章

      网友评论

          本文标题:SPI实现接口多实现路由

          本文链接:https://www.haomeiwen.com/subject/jyzinftx.html