SPI is all called (Service Provider Interface) and is a service delivery discovery mechanism built into the JDK. There are many frameworks that use it to do service expansion discovery, simply put, it is a dynamic substitution discovery mechanism, for example, there is an interface, want to run the dynamic to add to it implementation, you just need to add an implementation.
When the provider of the service provides an implementation of an interface, it is necessary to create a file named in the meta-inf/services/directory under Classpath, which is the specific implementation class of this interface. When other programs require this service, you can use the service by looking for the configuration file in the meta-inf/services/of the jar package (which is generally dependent on the jar package) and the specific implementation class name of the interface in the configuration file, which can be instantiated based on the class name. The tool class for finding the implementation of a service in the JDK is: Java.util.ServiceLoader.
SPI instance
Defining interfaces
Package Org.cellphone.api; Public Interface DataSource { String getconnection ();}
Oracle Vendor Implementation Interface
Package org.cellphone.oracle; Import Org.cellphone.api.DataSource; Public class Implements DataSource { @Override public String getconnection () { return "Oracle provides database connection pool";} }
And in the classpath under the meta-inf/services/directory with the interface full path name definition file: Org.cellphone.api.DataSource, the file content is:
Org.cellphone.oracle.DataSourceImpl
MySQL Vendor Implementation interface
Package Org.cellphone.mysql; Import Org.cellphone.api.DataSource; Public class Implements DataSource { @Override public String getconnection () { return "MySQL provides database connection pool";} }
And in the classpath under the meta-inf/services/directory with the interface full path name definition file: Org.cellphone.api.DataSource, the file content is:
Org.cellphone.mysql.DataSourceImpl
Serviceloader.load (datasource.class) Read Vendor Oracle, MySQL provides the files in the jar package, Serviceloader implements the Iterable interface through while The FOR Loop statement iterates through all implementations.
PackageOrg.cellphone.invoker;ImportOrg.cellphone.api.DataSource;ImportJava.util.ServiceLoader; Public classMain {Private Staticserviceloader<datasource> loader = serviceloader.load (DataSource.class); Public Static voidMain (string[] args) { for(DataSource source:loader) {System.out.println (source.getconnection ()); } }}
Java SPI (Service Provider Interface)