SPI mechanism of Java series

1 What is SPI

The full name of SPI is Service Provider Interface. It is a service provider discovery mechanism built into JDK, which can be used by third parties to implement or extend API. In fact, SPI is a dynamic loading mechanism implemented by the combination of "interface-based programming + strategy mode + configuration file".

The overall mechanism diagram is as follows:
insert image description here

2 Why is SPI needed?

In general, a certain module of the system often has multiple implementations (that is, based on a certain interface, there are multiple implementations), and the caller needs to dynamically enable or replace specific implementation strategies according to actual use needs, and certainly cannot directly use hardware The way of coding, because once the code involves a specific implementation class, it violates the principle of pluggability. If you need to replace an implementation, you need to modify the code. In this case, the SPI mechanism can be used: a mechanism to find a service implementation for an interface, so its core idea is decoupling .

3 Introduction

4 Advantages and disadvantages

4.1 Advantages

  • The advantage of using the Java SPI mechanism is to achieve decoupling, so that the logic of the assembly control of the third-party service module is separated from the business code of the caller, rather than coupled together. Applications can enable framework extensions or replace framework components according to actual business conditions.

4.2 Disadvantages

  • Although ServiceLoader can be regarded as lazy loading, it can only be obtained through traversal, that is, all implementation classes of the interface are loaded and instantiated once. If you don't want to use some implementation class, it is also loaded and instantiated, which causes waste. The way to obtain a certain implementation class is not flexible enough, it can only be obtained in the form of Iterator, and the corresponding implementation class cannot be obtained according to a certain parameter.
  • It is not safe for multiple concurrent multithreaded instances of the ServiceLoader class to be used.

Guess you like

Origin blog.csdn.net/qq_26822029/article/details/129090618