search
HomeJavajavaTutorialWhat is SPI mechanism in Java
What is SPI mechanism in JavaMay 17, 2023 pm 11:40 PM
javaspi

1: Introduction to SPI mechanism

SPI The full name is Service Provider Interface, which is a JDK built-in dynamic loading implementation extension point Mechanism, through SPI technology we can dynamically obtain the implementation class of the interface without creating it ourselves. This is not a special technology, just a design concept.

2: SPI principle

What is SPI mechanism in Java

Java SPI is actually a dynamic loading mechanism implemented by a combination of interface-based programming + strategy mode + configuration files.

There are often many different implementation solutions for various abstractions in system design. In object-oriented design, it is generally recommended that modules be programmed based on interfaces, and implementation classes should not be hard-coded between modules. If a specific implementation class is referenced in the code, then the principle of pluggability is violated. In order to implement the replacement, the code needs to be modified. A service discovery mechanism is needed to enable module assembly without dynamically specifying it in the program.

Java SPI provides a mechanism to find service implementations related to a certain interface. In modular design, a mechanism similar to the IOC idea is widely used, that is, the assembly control of components is transferred outside the program. So the core idea of ​​SPI is decoupling.

3: Usage Scenarios

The caller enables, extends, or replaces the framework’s implementation strategy according to actual usage needs

The following are some scenarios where this mechanism is used

  • JDBC driver, loading driver classes for different databases

  • Spring uses a lot of SPI, such as: the implementation of ServletContainerInitializer in the servlet3.0 specification, automatic Type Conversion SPI (Converter SPI, Formatter SPI), etc.

  • Dubbo also uses SPI extensively to implement framework extensions, but it encapsulates the native SPI provided by Java. Allow users to extend the implementation of the Filter interface

  • Tomcat loads the class that needs to be loaded under META-INF/services

  • Use the @SpringBootApplication annotation in the SpringBoot project , automatic configuration will start, and the startup configuration will scan the configuration class under META-INF/spring.factories

4: Source code demonstration

4.1 Application Call the ServiceLoader.load method

In the ServiceLoader.load method, first create a new ServiceLoader and instantiate the member variables in the class

    private static final String PREFIX = "META-INF/services/";


  private ServiceLoader(Class<S> svc, ClassLoader cl) {
        service = Objects.requireNonNull(svc, "Service interface cannot be null");
        loader = (cl == null) ? ClassLoader.getSystemClassLoader() : cl;
        acc = (System.getSecurityManager() != null) ? AccessController.getContext() : null;
        reload();
    }

	/** 
     * 
     * 在调用该方法之后,迭代器方法的后续调用将延迟地从头开始查找和实例化提供程序,就像新创建的加载程序所做的		  那样
     */
   public void reload() {
        providers.clear(); //清除此加载程序的提供程序缓存,以便重新加载所有提供程序。
        lookupIterator = new LazyIterator(service, loader);
    }

	private class LazyIterator implements Iterator<S>{

        Class<S> service;
        ClassLoader loader;
        Enumeration<URL> configs = null;
        Iterator<String> pending = null;
        String nextName = null;


        private boolean hasNextService() {
            if (nextName != null) {
                return true;
            }
            if (configs == null) {
                try {
                    //找到配置文件
                    String fullName = PREFIX + service.getName();
                    //加载配置文件中的内容
                    if (loader == null)
                        configs = ClassLoader.getSystemResources(fullName);
                    else
                        configs = loader.getResources(fullName);
                } catch (IOException x) {
                    fail(service, "Error locating configuration files", x);
                }
            }
            while ((pending == null) || !pending.hasNext()) {
                if (!configs.hasMoreElements()) {
                    return false;
                }
                //解析配置文件
                pending = parse(service, configs.nextElement());
            }
            //获取配置文件中内容
            nextName = pending.next();
            return true;
        }
    }

		/** 
     	* 
     	*  通过反射 实例化配置文件中的具体实现类
    	 */
		private S nextService() {
            if (!hasNextService())
                throw new NoSuchElementException();
            String cn = nextName;
            nextName = null;
            Class<?> c = null;
            try {
                c = Class.forName(cn, false, loader);
            } catch (ClassNotFoundException x) {
                fail(service,
                     "Provider " + cn + " not found");
            }
            if (!service.isAssignableFrom(c)) {
                fail(service,
                     "Provider " + cn  + " not a subtype");
            }
            try {
                S p = service.cast(c.newInstance());
                providers.put(cn, p);
                return p;
            } catch (Throwable x) {
                fail(service,
                     "Provider " + cn + " could not be instantiated",
                     x);
            }
            throw new Error();          // This cannot happen
        }

5: Practical combat

Step 1 Create the following class

public interface IService {

    /**
     * 获取价格
     * @return
     */
    String getPrice();

    /**
     * 获取规格信息
     * @return
     */
    String getSpecifications();
}
public class GoodServiceImpl implements IService {

    @Override
    public String getPrice() {
        return "2000.00元";
    }

    @Override
    public String getSpecifications() {
        return "200g/件";
    }
}
public class MedicalServiceImpl implements IService {

    @Override
    public String getPrice() {
        return "3022.12元";
    }

    @Override
    public String getSpecifications() {
        return "30粒/盒";
    }
}

Step 2, create the /META-INF/services directory under src/main/resources/, and add a file named after the interface org.example.IService.txt. The content is the implementation class to be applied. The data I need to put in is as follows

org.example.GoodServiceImpl
org.example.MedicalServiceImpl

Step 3, use ServiceLoader to load the implementation specified in the configuration file.

public class Main {
    public static void main(String[] args) {
        final ServiceLoader<IService> serviceLoader = ServiceLoader.load(IService.class);
        serviceLoader.forEach(service -> {
            System.out.println(service.getPrice() + "=" + service.getSpecifications());
        });
    }
}

Output:

2000.00 yuan=200g/piece
3022.12 yuan=30 capsules/box

6: Advantages and Disadvantages

6.1 Advantages

Decoupling separates the assembly control logic of the third-party service module from the caller's business code instead of coupling them together. The application can enable framework extension or replace the framework according to actual business conditions. components. Compared with the method of providing an interface jar package for third-party service modules to implement the interface, the SPI method allows the source framework to not need to care about the path of the interface implementation class

6.2 Disadvantages

  • Although ServiceLoader can be regarded as lazy loading, it can basically only be obtained through traversal, that is, all implementation classes of the interface are loaded and instantiated. If some implementation classes are loaded and instantiated but you don't need to use them, resources are wasted. The way to obtain a specific implementation class is too limited. It can only be obtained in the form of an iterator, and the corresponding implementation class cannot be obtained based on specific parameters.

  • Instances of multiple concurrent multi-threads using the ServiceLoader class are unsafe

The above is the detailed content of What is SPI mechanism in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
带你搞懂Java结构化数据处理开源库SPL带你搞懂Java结构化数据处理开源库SPLMay 24, 2022 pm 01:34 PM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于结构化数据处理开源库SPL的相关问题,下面就一起来看一下java下理想的结构化数据处理类库,希望对大家有帮助。

Java集合框架之PriorityQueue优先级队列Java集合框架之PriorityQueue优先级队列Jun 09, 2022 am 11:47 AM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于PriorityQueue优先级队列的相关知识,Java集合框架中提供了PriorityQueue和PriorityBlockingQueue两种类型的优先级队列,PriorityQueue是线程不安全的,PriorityBlockingQueue是线程安全的,下面一起来看一下,希望对大家有帮助。

完全掌握Java锁(图文解析)完全掌握Java锁(图文解析)Jun 14, 2022 am 11:47 AM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于java锁的相关问题,包括了独占锁、悲观锁、乐观锁、共享锁等等内容,下面一起来看一下,希望对大家有帮助。

一起聊聊Java多线程之线程安全问题一起聊聊Java多线程之线程安全问题Apr 21, 2022 pm 06:17 PM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于多线程的相关问题,包括了线程安装、线程加锁与线程不安全的原因、线程安全的标准类等等内容,希望对大家有帮助。

详细解析Java的this和super关键字详细解析Java的this和super关键字Apr 30, 2022 am 09:00 AM

本篇文章给大家带来了关于Java的相关知识,其中主要介绍了关于关键字中this和super的相关问题,以及他们的一些区别,下面一起来看一下,希望对大家有帮助。

Java基础归纳之枚举Java基础归纳之枚举May 26, 2022 am 11:50 AM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于枚举的相关问题,包括了枚举的基本操作、集合类对枚举的支持等等内容,下面一起来看一下,希望对大家有帮助。

java中封装是什么java中封装是什么May 16, 2019 pm 06:08 PM

封装是一种信息隐藏技术,是指一种将抽象性函式接口的实现细节部分包装、隐藏起来的方法;封装可以被认为是一个保护屏障,防止指定类的代码和数据被外部类定义的代码随机访问。封装可以通过关键字private,protected和public实现。

归纳整理JAVA装饰器模式(实例详解)归纳整理JAVA装饰器模式(实例详解)May 05, 2022 pm 06:48 PM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于设计模式的相关问题,主要将装饰器模式的相关内容,指在不改变现有对象结构的情况下,动态地给该对象增加一些职责的模式,希望对大家有帮助。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment