dubbo可扩展的点的类的对象创建 都是用类似javaspi的思想来做的。所以看后面代码 先熟悉一下java的SPI实现
如ServicesConfig的代码
private static final Protocol protocol = (Protocol)ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension();
JAVASPI的作用
服务(接口实现类)的自动发现。我们定义好一组接口标准。而具体实现调用者根据自身需求自己实现
JavaSPI简单使用
我们模拟我们做了一个框架(jar) 框架的正常运行需要相关配置。配置加载方式由使用者来实现
1.定义接口
/** * 加载配置文件的句柄 */ public interface LoadConfigHandle { public String load(); }
2.定义实现类
public class HttpLoadConfigHandle implements LoadConfigHandle { public String load() { System.out.println("正在用http请求加载配置文件数据"); return ""; } }
public class XmlLoadConfigHandle implements LoadConfigHandle { public String load() { System.out.println("正在加载配置文件xml"); return ""; } }
在resource创建META-INF文件夹,再创建一个与接口全名称同名的文件。将实现类配置进去
com.liqiang.spi.XmlLoadConfigHandle
com.liqiang.spi.HttpLoadConfigHandle
3测试
public static void main(String[] str) throws InterruptedException { ServiceLoader<LoadConfigHandle> serviceLoader = ServiceLoader.load(LoadConfigHandle.class); Iterator<LoadConfigHandle> iterator = serviceLoader.iterator(); while (iterator.hasNext()) { LoadConfigHandle loadConfigHandle = iterator.next(); loadConfigHandle.load(); } }