SPI definition: Full name service Provider Interface. The technical term is: services provide interfaces. In plain English: specific implementation classes can be loaded based on a given interface. Generally used as an interface for third-party implementations or extensions.

Advantages:

Decoupling. Extensions can be implemented without changing the source code. It’s not invasive. Extension also does not need to change the original code only need to add configuration to achieve extension, in line with the open closed principle (open for extension, closed for modification).

Disadvantages:

1. The meta-INF /services directory is invalid

2. Only all implementations can be traversed in code, and all examples. If you don’t all need implementation classes, you waste performance.

3. The contents of the interface name file can be configured for all extension implementations without naming (alias). Having multiple implementation classes makes the program difficult to find.

Example:

Define an interface

public interface Person {
    String say();
}
Copy the code

2. The interface implements two implementation classes

Public class woman implements Person {@override public String say() {system.out.println (" I am a woman "); }} public implements Person {@override public String say() {system.out.println (" I am a Man "); }}Copy the code

Create meta-INF /services on the classpath and add a file named meta-INF /services with the fully qualified name of the interface

The file content is the fully qualified name of the interface implementation class, which can have more than one implementation class

Add a main class

public class mainApp { public static void main(String[] args) { ServiceLoader<Person> persons = ServiceLoader.load(Person.class); for (Person person: persons ) { System.out.println(person.say()); }}}Copy the code

5. Execution results