千家信息网

JVM中SPI的概念和应用

发表于:2025-02-02 作者:千家信息网编辑
千家信息网最后更新 2025年02月02日,本篇内容主要讲解"JVM中SPI的概念和应用",感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习"JVM中SPI的概念和应用"吧!概念Service Provid
千家信息网最后更新 2025年02月02日JVM中SPI的概念和应用

本篇内容主要讲解"JVM中SPI的概念和应用",感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习"JVM中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 providers = Service.providers(SPIService.class);        ServiceLoader load = ServiceLoader.load(SPIService.class);        while (providers.hasNext()){            SPIService ser = providers.next();            ser.execute();        }        System.out.println("-----------------------");        Iterator iterator = load.iterator();        while (iterator.hasNext()){            SPIService ser = iterator.next();            ser.execute();        }    }}

输出

SpiImpl1.execute()SpiImpl2.execute()-----------------------SpiImpl1.execute()SpiImpl2.execute()

到此,相信大家对"JVM中SPI的概念和应用"有了更深的了解,不妨来实际操作一番吧!这里是网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

0