SPI mechanism

SPI is actually a good agreement norms, regulations and good at META-INF under the classpath / services / path, placing specify a class specified interface, and provides ServiceLoader java class, which will go to read the file, and then file specified in the interface implementation class, then class.forName () to load the class.
Always: javase agreement is a good standard, then you can pass serviceLoader, to find a specific category.
In this way, can be directly called with the interface, then who wants to achieve their functions, will come to realize this interface, and then implement this interface classes into META-INF / services / path just fine.

Here is an example of a online:

public interface IShout {
    void shout();
}
public class Dog implements IShout {
    @Override
    public void shout() {
        System.out.println("wang wang");
    }
}
public class Cat implements IShout {

    @Override
    public void shout() {
        System.out.println("miao miao");
    }
}
META-INF/services/org.foo.demo.IShout文件内容
org.foo.demo.Dog
org.foo.demo.Cat

测试
public class SPIMain {
    public static void main(String[] args) {
        ServiceLoader<IShout> shouts = ServiceLoader.load(IShout.class);
        for (IShout s : shouts) {
            s.shout();
        }
    }
}

Since it is a good agreement norm, so, naturally, you can also agreed to a good standard, then do yourself a similar serviceLoader loader, and then to load the implementation class can, as long as, let others follow this specification just fine.

For example, dubbo:
For Protocal interface provides implementation classes:
/META_INF/dubbo/internal/com.alibaba.dubbo.rpc.Protocol
then through their own loader, load would be finished.
Protocol protocol = ExtensionLoader.getExtensionLoader (Protocol.class) .getAdaptiveExtension ();

Why dubbo to realize their spi it?
Because, dubbo need an interface to provide multiple implementation classes, then by way of comment, which specifies the implementation class to use.
For example, it /META_INF/dubbo/internal/com.alibaba.dubbo.rpc.Protocol contents of the documents:

dubbo=com.alibaba.dubbo.rpc.protocol.dubbo.DubboProtocol
http=com.alibaba.dubbo.rpc.protocol.http.HttpProtocol
hessian=com.alibaba.dubbo.rpc.protocol.hessian.HessianProtocol

Properties in a manner to achieve class provides an identifier, then @SPI ( "dubbo") in such a way, to achieve the specified implementation class loading, and this way, the java carrying spi impossible.

@SPI("dubbo")  
public interface Protocol {  
    int getDefaultPort();  
    @Adaptive  
    <T> Exporter<T> export(Invoker<T> invoker) throws RpcException;  
    @Adaptive  
    <T> Invoker<T> refer(Class<T> type, URL url) throws RpcException;  
    void destroy();  
} 

Reference: https://juejin.im/post/5af952fdf265da0b9e652de3

Reproduced in: https: //www.jianshu.com/p/1a301ae3c650

Guess you like

Origin blog.csdn.net/weixin_34080571/article/details/91202644