The full name of the SPI is Service Provider Interface. This is for the manufacturer or plugin. Generally speaking, for the unknown implementation or to expand the open system, usually some things are abstracted out, abstract each module, often have many different implementations, such as log module scheme, XML parsing module, JDBC module scheme. This can be understood by our abstract factory approach, which can be implemented by vendors or developers themselves. Because the code is in the upper layer of a wrapper, is not know how to implement the bottom, then only through the form of SPI, let the upper level know which abstract should be called the specific implementation. So it can be understood that in some jar packages, a way to use for other development extension calls is to provide a specific implementation for an interface or service.
Mainly used to serviceloader this class, serviceloader by reading resources/meta-inf/services/ The Xxxservice SPI implementation class under the Com.xxx.xxx.xxxService file, obtains the corresponding class instance through the reflection, and invokes the corresponding method.
public class Searchfactory {
private searchfactory () {
} public
static Search NewSearch () {
Search search = null;
serviceloader<search> Serviceloader = Serviceloader.load (Search.class);//Find the implementation of the SPI
Iterator<search > searchs = Serviceloader.iterator ();
if (Searchs.hasnext ()) {
search = Searchs.next ();
}
if (search = = null) {//If there is no SPI implementation, the
ClassLoader ClassLoader = Thread.CurrentThread () is implemented with the default class object. Getcontextclassloader ();
try {
search = (search) classloader.loadclass (search.defaultsearchclass). newinstance ();
} catch ( ClassNotFoundException e) {
e.printstacktrace ();
} catch (Instantiationexception e) {
E.printstacktrace ();
} catch (Illegalaccessexception e) {
e.printstacktrace ();
}
}
return search;
}
Usage scenarios are:
1, Javax.xml.ws.spi.Provider, this class can use another implementation, such as Com.sun.xml.internal.ws.spi.ProviderImpl.
Here we need the resources directory under Engineering, build a meta-inf/services directory, Then create a file name of Javax.xml.ws.spi.Provider, the file content is Com.sun.xml.internal.ws.spi.ProviderImpl. If there is no default implementation for the SPI, an error will be made, and you need to add this in the format above.
For more information about SPI, you can view a simple code I wrote, very simple. Thank you for your support.
GitHub Code: Https://github.com/zhuzhenke/java-spi-test