JDK SPI mechanism
1、 Overview
We first saw the SPI mechanism in the implementation of Dubbo. Recently, we found that it is not a new thing. It is actually a built-in thing in JDK. Let's find out today and see what it is!
The full name of SPI is service provider interface, which is a service discovery mechanism. It finds the service implementation in the meta inf / services folder under the classpath path and automatically loads the interface implementation classes defined in the file.
2、 Realize
First, we define an interface helloservice Java and its two implementation classes helloserviceimpla java、HelloServiceImplB. java
public interface HelloService {
void hello();
}
public class HelloServiceImplA implements HelloService {
@Override
public void hello() {
System.out.println("Hello! I am ImplA");
}
}
public class HelloServiceImplB implements HelloService {
@Override
public void hello() {
System.out.println("Hello! I am ImplB");
}
}
Next, we need to create a new file under meta inf / services. The file name is the full class name of the interface, and the file content is the full class name of the interface implementation class (multiple implementation classes are represented by line feed).
Finally, it is the service discovery process. We need to use the serviceloader class.
public class HelloServiceTest {
public static void main(String[] args) {
ServiceLoader<HelloService> serviceLoader = ServiceLoader.load(HelloService.class);
Iterator<HelloService> iterator = serviceLoader.iterator();
while (iterator.hasNext()) {
HelloService helloService = iterator.next();
helloService.hello();
}
}
}
3、 Summary
What do you think? This way of not declaring the interface implementation in the program, but also initiating the call, is it refreshing!
The underlying implementation of SPI basically uses the reflection mechanism, which is implemented through the full class name instantiation interface to initiate the call.
SPI mechanism makes it possible for many framework extensions. For example, SPI mechanism is used in Dubbo and JDBC.