Java SPI example
The principle of SPI mechanism is briefly introduced in the previous section. In this section, an example is used to demonstrate the use of Java SPI. First, we define an interface called Robot.
public interface Robot { void sayHello(); }
Next, we define two implementation classes, Optimus Prime and Bumblebee.
public class OptimusPrime implements Robot { @Override public void sayHello() { System.out.println("Hello, I am Optimus Prime."); } } public class Bumblebee implements Robot { @Override public void sayHello() { System.out.println("Hello, I am Bumblebee."); } }
Next, create a file under the META-INF/services folder, with the fully qualified name of Robot org.apache.spi.Robot. The file content is the fully qualified class name of the implementation class, as follows:
org.apache.spi.OptimusPrime org.apache.spi.Bumblebee
Do the necessary preparations, then write the code for testing.
public class MainTSpi { public static void main(String[] args) { ServiceLoader<Robot> serviceLoader = ServiceLoader.load(Robot.class); System.out.println("Java SPI"); serviceLoader.forEach(Robot::sayHello); } }
extend
At this time, we add an interface imp l ementation time
Such as:
public class RATCHET implements Robot{ @Override public void sayHello() { System.out.println("Hello, I am RATCHET."); } }
The interface is updated by the following code: (the update will not run at the same time, but the newly implemented interface will be executed at the next call, and the same interface will only be executed once)
/** * @description: * @author: Mr.Dai * @create: 2020-05-01 21:36 **/ public class MainTSpi { public static void main(String[] args) throws IOException { ServiceLoader<Robot> serviceLoader = ServiceLoader.load(Robot.class); System.out.println("Java SPI"); serviceLoader.forEach(Robot::sayHello); /** Let's say we rewrite the configuration file */ String path=System.getProperty("user.dir")+"\\java-important_question\\src\\main\\resources\\META-INF\\services\\com.dgwcode.spi.Robot"; BufferedWriter writer = new BufferedWriter(new FileWriter(path,true)); writer.write("\ncom.dgwcode.spi.RATCHET"); writer.close(); serviceLoader.reload(); serviceLoader.forEach(Robot::sayHello); } }
First run
Java SPI Hello, I am Optimus Prime. Hello, I am Bumblebee. Hello, I am Optimus Prime. Hello, I am Bumblebee.
Second operation
Java SPI Hello, I am Optimus Prime. Hello, I am Bumblebee. Hello, I am RATCHET. Hello, I am Optimus Prime. Hello, I am Bumblebee. Hello, I am RATCHET.
Profile content:
com.dgwcode.spi.OptimusPrime com.dgwcode.spi.Bumblebee com.dgwcode.spi.RATCHET com.dgwcode.spi.RATCHET