1. What is the SPI for Java
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.
Specifically, in the jar package "src/meta-inf/services/" directory to create a file, the file name is the fully qualified name of the interface, the contents of the files can have more than one line, each line is the interface corresponding to the specific implementation class of the fully qualified name.
2. Application Scenarios
For example, you want to extend some of the framework, such as some of spring's functions, to implement its interface, and then configure it yourself.
3. Example code
Define the interface first:
Package Com.ming.spi.service; /** @author*/Publicinterface dogservice { void sleep ();}
Then define two implementations:
package Com.ming.spi.service.imp; import Com.ming.spi.service.DogService; public class Blackdogserviceimpl implements dogservice{@ Override public void sleep () {System.out.println ( "Black dog ... Bark, don't sleep ... "); } }
Package Com.ming.spi.service.imp; Import Com.ming.spi.service.DogService; Public class Implements dogservice{ @Override publicvoid sleep () { System.out.println ( "White dog ... Go to sleep ... "); }
Finally, a test code:
Package Com.ming.spi.service; Import Java.util.ServiceLoader; Public class Test { publicstaticvoidthrows Exception { Serviceloader<DogService> loaders = Serviceloader.load (dogservice. Class); for (Dogservice d:loaders) { d.sleep (); }}}
Then the code in the Src/meta-inf/services/com.ming.spi.service.dogservice file:
Com.ming.spi.service.imp.BlackDogServiceImplcom.ming.spi.service.imp.WhilteDogServiceImpl
The final run result is the two implementations you need.
Finally, summarize:
Java's SPI run process is to use the Java.util.ServiceLoader class load method to find the corresponding full path interface name file in src/meta-inf/services/, then find the corresponding implementation method in the file and inject the implementation, Then you can use the
Reference: http://www.cnblogs.com/zhongkaiuu/articles/5040971.html
The more you use it, the more things you don't know ... Slowly in soy sauce ...
Simple application of the SPI in Java