• 【深入浅出-JVM】(77):SPI


    概念

    Service Provider Interface

    规则

    1. 在resource/META-INF/services 创建一个以接口全限定名为命名的文件,内容写上实现类的全限定名
    2. 接口实现类在classpath路径下
    3. 主程序通过 java.util.ServiceLoader 动态装载实现模块(扫描META-INF/services目录下的配置文件找到实现类,装载到 JVM)

    好处

    解耦,主程序和实现类之间不用硬编码

    例子

    package com.mousycoder.mycode.thinking_in_jvm;
    
    /**
     * @version 1.0
     * @author: mousycoder
     * @date: 2019-09-16 16:14
     */
    public interface SPIService {
        void execute();
    }
    
    
    package com.mousycoder.mycode.thinking_in_jvm;
    
    /**
     * @version 1.0
     * @author: mousycoder
     * @date: 2019-09-16 16:16
     */
    public class SpiImpl1 implements SPIService {
        @Override
        public void execute() {
            System.out.println("SpiImpl1.execute()");
        }
    }
    
    
    package com.mousycoder.mycode.thinking_in_jvm;
    
    /**
     * @version 1.0
     * @author: mousycoder
     * @date: 2019-09-16 16:16
     */
    public class SpiImpl2 implements SPIService {
        @Override
        public void execute() {
            System.out.println("SpiImpl2.execute()");
        }
    }
    
    

    在 resources/META-INF/services/目录下创建文件名为com.mousycoder.mycode.thinking_in_jvm.SPIService的文件,内容
    com.mousycoder.mycode.thinking_in_jvm.SpiImpl1
    com.mousycoder.mycode.thinking_in_jvm.SpiImpl2

    主程序

    package com.mousycoder.mycode.thinking_in_jvm;
    
    import sun.misc.Service;
    
    import java.util.Iterator;
    import java.util.ServiceLoader;
    
    /**
     * @version 1.0
     * @author: mousycoder
     * @date: 2019-09-16 16:21
     */
    public class SPIMain {
    
        public static void main(String[] args) {
            Iterator<SPIService> providers = Service.providers(SPIService.class);
            ServiceLoader<SPIService> load = ServiceLoader.load(SPIService.class);
    
            while (providers.hasNext()){
                SPIService ser = providers.next();
                ser.execute();
            }
    
            System.out.println("-----------------------");
            Iterator<SPIService> iterator = load.iterator();
            while (iterator.hasNext()){
                SPIService ser = iterator.next();
                ser.execute();
            }
        }
    }
    
    

    输出

    SpiImpl1.execute()
    SpiImpl2.execute()
    -----------------------
    SpiImpl1.execute()
    SpiImpl2.execute()
    
    我是浩哥,希望我的思考能帮到您!
  • 相关阅读:
    docker的核心概念、docker的安装与卸载
    centos 7 配置yum源
    杂记
    linux命令之rpm(软件的安装卸载)
    chrony服务及cobbler+pxe实现自动化装机
    sshd登录控制脚及本sudo权限设置
    selinux控制脚本、AWK应用、监控访问脚本实例
    排除GC引起的CPU飙高
    POI报表导入导出
    逆向学习之环境准备
  • 原文地址:https://www.cnblogs.com/mousycoder/p/11528958.html
Copyright © 2020-2023  润新知