Thanks a lot, http://blog.csdn.net/quhongwei_zhanqiu/article/details/41577159.
Dubbo adopts micro-kernel + plug-in system, which makes the design elegant and strong in extensibility. How does the so-called micro-kernel + plug-in system be implemented? Are you familiar with the SPI (service providerinterface) mechanism, that is, we define the interface standards, let the manufacturer to implement (if you do not know the SPI, Google Baidu), the JDK through the Serviceloader class implementation of the SPI mechanism of service lookup function.
JDK Implementation SPI Service lookup: Serviceloader
First define the following example interface
Package com.example;
Public interface Spi {
boolean issupport (String name);
String SayHello ();
}
Serviceloader will traverse all jars to find the Meta-inf/services/com.example.spi file
A vendor provides implementation
Package com.a.example;
public class Spiaimpl implements SPI {public
boolean issupport (String name) {
return ' Spia '. Equalsignorecase ( Name.trim ());
}
Public String Syahello () {
return "Hello I am Vendor a";
}
}
The contents of the Meta-inf/services/com.example.spi file in the jar package provided by a vendor are:
Com.a.example.spiaimpl #厂商A的spi实现全路径类名
b manufacturers to provide the implementation
Package com.b.example;
public class Spibimpl implements SPI {public
boolean issupport (String name) {
return ' SPIB '. Equalsignorecase ( Name.trim ());
}
Public String Syahello () {
return "Hello I am Vendor B";
}
}
The contents of the Meta-inf/services/com.example.spi file in the jar package provided by Vendor B are:
Com.b.example.spibimpl #厂商B的spi实现全路径类名
Serviceloader.load (Spi.class) reads vendor A, B provides the files in the jar package, Serviceloader implements the Iterable interface to traverse all implementations through the while for Loop statement.
A multiple implementation of an interface, as the policy mode provides the implementation of the policy, but does not provide a choice of policy, the user can be based on the Issupport method according to the business to the name of the vendor to select specific vendors.
public class Spifactory {
//Read Config Get all implementations
private static Serviceloader Spiloader = Serviceloader.load (Spi.class);
//select corresponding by name to implement public
static Spi Getspi (String name) {for
(Spi spi:spiloader) {
if (Spi.issupport (name) ) {
return SPI;
}
}
return null;
}
}