Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the meaning of SPI in JAVA

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces the meaning of SPI in JAVA, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let the editor take you to understand it.

1. SPI introduction

The full name of SPI is Service Provider Interface, which is a set of interfaces provided by Java to be implemented or extended by third parties. Its significance is to find the implementation of services for an interface. It is mainly used in the framework to find components and improve scalability.

Automobile manufacturing is a relatively tedious process, the usual means is to first specify the production specifications of automobile parts, various parts manufacturers in accordance with these rules to produce qualified parts. The car manufacturer selects the right parts to assemble to produce the car. Even if a part of the car is damaged, you don't have to abandon the whole car, you just need to replace the component.

SPI is a mechanism used to find auto parts, production specification is the definition of interface, component manufacturers produce parts according to the interface to provide specific implementation, SPI selects appropriate components for assembly to complete specific functions, when a component has loopholes or problems, it can replace components without changing the code to improve scalability.

2. SPI rules

SPI aims to find the implementation of a service for an interface, so the interface of the component should be defined at the beginning of the design. The steps for using the SPI mechanism of JAVA are as follows:

Define component interfaces (production specifications)

Implement component interfaces (provide components)

Configure component files (find components)

Reflection instance invocation (assembly work)

3. SPI case

Define the specification of component development in the component definition project, that is, define which interface components need to be implemented by the component A project and component B project to provide the implementation of the component, that is, to implement the interface component definition of the component application project to select the appropriate component to use the component.

3.1 definition of components

Define the specification of the component in the [commons-api] project, that is, define the interface. The name of the interface is ComponentService. The content is as follows:

Public interface ComponentService {/ * get the name of the component * @ return component name * / String getComponentName ();} 3.2 component implementation

In the [component-A] project, the component is provided according to the specification of the component definition, that is, the implementation of the component definition interface. The class name is ComponentA, and the content is as follows:

Public class ComponentA implements ComponentService {/ * component name * / private static final String COMPONENT_NAME = "component A"; @ Override public String getComponentName () {return COMPONENT_NAME;}}

According to the SPI rules of JAVA, create a new file under the resource/META-INF/services resource directory of [component-A] project. The file name is the fully qualified name of the component interface, and the content is the fully qualified name of the component implementation.

The corresponding component implementation is also provided in the [component-B] project. The class name is ComponentB, and the content is as follows:

Public class ComponentB implements ComponentService {/ * component name * / private static final String COMPONENT_NAME = "component B"; @ Override public String getComponentName () {return COMPONENT_NAME;}}

Also configure the file under the resource/META-INF/services resource directory of the [component-B] project

3.3 selection of components

The java project built on maven uses pom files to orchestrate the dependent components needed by the project. Now it needs components, and I think component An is more suitable for me than component B. for example, I arranged component An in the pom of [component-application] project, which is as follows:

Com.xxxx component-A 1.0-SNAPSHOT

Create a new application startup class in the [component-application] project to use the component. The class name is Main, and the content is as follows:

Public class Main {public static void main (String [] args) {/ / load component ServiceLoader components = ServiceLoader.load (ComponentService.class); for (ComponentService component: components) {/ / Application component: print component name System.out.println (component.getComponentName ());}

Start the main method of the Main class of the [component-application] project, and the result is as follows:

If one day I find that there is a big loophole in component A, I need to replace component A with component B. you only need to remove the dependency of component An in the pom of [component-application] project and import the dependency of component B. the content of pom is as follows:

Com.xxxx component-B 1.0-SNAPSHOT

You do not need to modify the specific usage details of the [component-application] project to replace the components. Run as follows:

4. SPI principle

The SPI mechanism provided by JAVA mainly depends on the java.util.ServiceLoader class, starting from the SPI case, enter the ServiceLoader.load method to find out.

The load method will eventually create an instance of LazyIterator. When you see Iterator, you probably know that it has something to do with iterators. Let's continue to know what LazyIterator is.

It's a good guess that LazyIterator is related to iterators, which is an inner class of ServiceLoader that implements the Iterator interface, so you only need to focus on the methods defined by the Iterator interface.

Public boolean hasNext () public S next ()

The hasNext method defined by the Iterator interface is used to determine whether there is any next element in the iteration, and the hasNext method of LazyIterator is ultimately the called hasNextService method, focusing on this.

Obtain the fully qualified name of the component implementation of the resource file configuration in the specified directory through the class loader, and store it in a container variable of configs. With the fully qualified name of the component implementation, most of the reflection generated object is returned. Take a look at the next method of LazyIterator. The main logic of the next method of LazyIterator is in the nextService method. Analyze it carefully.

Consistent with the guess just now, the fully qualified name of the component implementation is used to generate the component object through Class.forName, so the program gets the object through the for loop that can be called.

5. SPI requirements

This is how the java.util.ServiceLoader class describes itself

A simple service-provider loading facility.

A simple service provider loading tool

The only requirement enforced by this facility is thatprovider classes must have a zero-argument constructor so that they can beinstantiated during loading

The only requirement for enforcement is that the provider class must have a parameterless constructor so that they can be instantiated during loading, as can be seen from the instance object generated by Class.forName.

6. SPI application

SPI's idea of component replacement is easily reminiscent of the JDBC specification that we are familiar with. JDBC is the JAVA standard for applications to connect to the database, defining several interfaces to connect to the database, such as Connection, Statement, and ResultSet. Each database vendor provides its own JDBC implementation, which is what we call database driver. Developers only need to care about how to use the various interfaces of JDBC, and do not need to learn the implementation of different vendors, which is interface-oriented programming.

JDBC programming is divided into four steps. SPI has been applied in the driver manager DriverManager.

Both Mysql driver and SqlServer driver have SPI configuration.

In the loadInitialDrivers method of the driver manager, the available drivers are obtained through the SPI mechanism, and the loadInitialDrivers method is called in the static code block. Here, it is not instantiated by fully qualified name reflection. The real driver registration is that the driver is registered in the registeredDrivers collection variable in the driver manager through the static code block in the driver class provided by the database vendor. Take the MySQL driver as an example:

In the getConnection method of the driver manager, it iterates through the available drivers found by SPI and gets the link through the driver until the link is successfully obtained.

Thank you for reading this article carefully. I hope the article "what is the meaning of SPI in JAVA" shared by the editor will be helpful to you. At the same time, I also hope that you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report