spi是jdk内置功能,dubbo也用了spi机制,我目前觉着,说白了就是多态思想,我定义个接口 ,这个是规范,具体实现你们来整,我不管。
- spi 简单实用案例
先定一个规范发布项目:
代码:
package com.liaoyang; public interface DriverInteface { void sayHello(String msg); }
再弄个项目,这个项目是来实现规范的
这里能实现spi_driver的接口,是因为把他的项目在maven里引用过来了,这里不写pom了
接下来,需要创建目录,写个文件,文件里面写上实现类的全路径
然后去规范方去试试,要在规范方引入实现方的依赖(这里只是为了演示,循环依赖实际不随便搞)
public class App { public static void main( String[] args ) { ServiceLoader<DriverInteface> serviceLoader = ServiceLoader.load(DriverInteface.class); for (DriverInteface driverInteface:serviceLoader) { driverInteface.sayHello("liaoyang"); } } }
运行:
C:Javajdk1.8.0_181injava.exe "-javaagent:C:Program FilesJetBrainsIntelliJ IDEA 2018.2libidea_rt.jar=59860:C:Program FilesJetBrainsIntelliJ IDEA 2018.2in" -Dfile.encoding=UTF-8 -classpath C:Javajdk1.8.0_181jrelibcharsets.jar;C:Javajdk1.8.0_181jrelibdeploy.jar;C:Javajdk1.8.0_181jrelibextaccess-bridge-64.jar;C:Javajdk1.8.0_181jrelibextcldrdata.jar;C:Javajdk1.8.0_181jrelibextdnsns.jar;C:Javajdk1.8.0_181jrelibextjaccess.jar;C:Javajdk1.8.0_181jrelibextjfxrt.jar;C:Javajdk1.8.0_181jrelibextlocaledata.jar;C:Javajdk1.8.0_181jrelibext ashorn.jar;C:Javajdk1.8.0_181jrelibextsunec.jar;C:Javajdk1.8.0_181jrelibextsunjce_provider.jar;C:Javajdk1.8.0_181jrelibextsunmscapi.jar;C:Javajdk1.8.0_181jrelibextsunpkcs11.jar;C:Javajdk1.8.0_181jrelibextzipfs.jar;C:Javajdk1.8.0_181jrelibjavaws.jar;C:Javajdk1.8.0_181jrelibjce.jar;C:Javajdk1.8.0_181jrelibjfr.jar;C:Javajdk1.8.0_181jrelibjfxswt.jar;C:Javajdk1.8.0_181jrelibjsse.jar;C:Javajdk1.8.0_181jrelibmanagement-agent.jar;C:Javajdk1.8.0_181jrelibplugin.jar;C:Javajdk1.8.0_181jrelib esources.jar;C:Javajdk1.8.0_181jrelib t.jar;E:gupaovipspi_driver argetclasses;D:my_maven_local_repositorycomliaoyangcom.liaoyang1.0-SNAPSHOTcom.liaoyang-1.0-SNAPSHOT.jar com.liaoyang.App
liaoyang say hello to spi world Process finished with exit code 0
Dubbo SPI 原理很接近
在dubbo项目里面,来试试扩展dubbo协议,先写个类,继承Protocol,这里改了默认端口。
然后就完事儿了,运行下程序
public class App { public static void main( String[] args ) { System.out.println( "Hello World!" ); Protocol liaoyangprotocal = ExtensionLoader.getExtensionLoader(Protocol.class) .getExtension("liaoyangprotocal"); System.out.println(liaoyangprotocal.getDefaultPort()); } }
运行 发现自定义的类已经被加载了