Java SPI介绍

一、SPI的全名为Service Provider Interface,是JDK内置的一种机制,是一种动态服务发现的机制。

基本思路是ServiceLoader负责读取写死路径下的配置然后将其中的类加载进行执行,当然这种服务面对的是接口层次。

基本代码层次如下:



 
core.spi.HelloInterface 内容:

core.impl.LiMingHello
core.impl.WangChaoHello

 Main 函数:

package core;

import java.util.ServiceLoader;

import core.spi.HelloInterface;
/**
 * SPI 服务
 *
 */
public class SPIMain {

	public static void main(String[] args) throws InterruptedException {

		
		while (true) {
			ServiceLoader<HelloInterface> loaders = ServiceLoader.load(HelloInterface.class);
			for (HelloInterface in : loaders) {
				in.sayHello();
			}
			Thread.sleep(2000);
		}
	}

}

其中有个死循环是为了测试其动态性,当其中删除一行实现只会输出其中一个实现类,说明其中实现类是动态加载。其中真正的使用场景可以参看dubblo源码。

猜你喜欢

转载自takemind.iteye.com/blog/2342304