深入浅出JVM77SPI

5次阅读

共计 1664 个字符,预计需要花费 5 分钟才能阅读完成。

概念

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()

正文完
 0