1. Demonstration case
Github: dubbo-demo-spi
JDK ServiceLoader example
ServiceLoaderMain class: the test entry of ServiceLoader.
ServiceLoaderInterface interface: define an interface, the specific implementation is defined in the resources/META-INF/services/com.alibaba.dubbo.demo.ServiceLoaderInterface directory.
Dubbo SPI example
SPIMain class: the test entry of SPI.
SPIService interface: define an @SPI interface, the specific implementation is defined in the resources/META-INF/dubbo/internal/com.alibaba.dubbo.demo.SPIService directory.
2. Relevant solutions
@SPI
Description: Annotation is on the class and is used to define an interface.
Case: The Transporter interface uses @SPI("netty") annotation, and its implementation is defined in the resources/META-INF/dubbo/internal/com.alibaba.dubbo.remoting.Transporter directory.
@Adaptive
Description: When the annotation is on the class, the instance object can be obtained through ExtensionLoader#getAdaptiveExtension(); when the annotation is on the method, the implementation class is determined by parameters.
@Activate
Description: The annotation is on the class, and when the group parameter matches, the implementation is activated.
Case: Filter interface uses @SPI annotation, and its implementation class ActiveLimitFilter uses @Activate annotation. When group="consumer", the filter is activated.
3. Core class: ExtensionLoader
- ExtensionLoader#getExtension(String): Get the implementation class object by name.
- ExtensionLoader#getAdaptiveExtension(): Get the implementation class object with @Adaptive annotation in the implementation class.
- ExtensionLoader#injectExtension(T): Use dependency injection to inject objects.
- ExtensionLoader#createAdaptiveExtensionClassCode(): When there is an @Adaptive annotation on the method, the implementation class string needs to be automatically generated for the extension point interface.
- ExtensionLoader#getActivateExtension(URL url, String key, String group): filter the implementation class objects that contain @Activate annotation and the group attribute matches.