Java-SPI mechanism

Introduction to SPI

The full name of SPI (Service Provider Interface) is a service provider discovery mechanism built into the JDK. At present, many frameworks use it for service extension discovery. In short, it is a mechanism for dynamic replacement of discovery. For example, if there is an interface, and you want to dynamically add implementation to it at runtime, you only need to An implementation needs to be added,

 

A simple example to illustrate how SPI is used. First, let's see through a picture, what specifications need to be followed when using SPI, because spi is a standard of JDK after all, and the Dubbo framework currently provides extended functions based on the SPI mechanism.


 

SPI implementation



 

1. First, create the spi interface class

We first create the spi interface class, such as creating the HelloInterface sample interface

package org.bird.spi;

/**
 * @description java spi(Service Provider Interface)样例
 * @author liangjf
 *
 */
public interface HelloInterface {

	/**
	 *
	 */
	public void sayHello();
}

2. Second, create a spi implementation class

We create two different implementation classes of ImageHello and TextHello of the spi interface respectively

package org.bird.spi.impl;

import org.bird.spi.HelloInterface;

public class ImageHello implements HelloInterface {

	public void sayHello() {
		System.out.println("Image Hello.");
	}

}

 

package org.bird.spi.impl;

import org.bird.spi.HelloInterface;

public class TextHello implements HelloInterface {

	public void sayHello() {
		System.out.println("Text Hello.");
	}

}

3. Again, create the meta directory

We create the META-INFO/services directory, and create a configuration file, the file name is interface/abstract class: full name File content: interface/abstract class implementation class is like this: org.bird.spi.HelloInterface



 

4. Finally, create a test program

We finally create a test program for spi to see if it meets our expected results.

package org.bird.spi;

import java.util.ServiceLoader;

public class SPIMain {

	public static void main(String[] args) {
		  ServiceLoader<HelloInterface> loaders = ServiceLoader.load(HelloInterface.class);  
		  for(HelloInterface in : loaders) {
			  in.sayHello();
		  }
	}

}

 The results are as follows:

Text Hello.
Image Hello.

 

 

 

 

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326346697&siteId=291194637