Home > Java > javaTutorial > How to implement SpringBoot's SPI mechanism

How to implement SpringBoot's SPI mechanism

WBOY
Release: 2023-05-16 09:10:11
forward
960 people have browsed it

    Introduction

    SPI (Service Provider Interface) is a service discovery mechanism built into JDK, which can be used to enable framework extensions and replacement components. Mainly For development in frameworks, such as Dubbo, Spring, Common-Logging, JDBC, etc., the SPI mechanism is used to provide different implementations for the same interface to different users, thus improving the scalability of the framework.

    Java SPI implementation

    Java's built-in SPI uses the java.util.ServiceLoader class to parse files named with the fully qualified name of the interface in the classPath and META-INF/services/ directories of the jar package. And load the interface implementation class specified in the file to complete the call.

    Example description

    Create a dynamic interface

    public interface VedioSPI
    {
        void call();
    }
    Copy after login

    Implementation class 1

    public class Mp3Vedio implements VedioSPI
    {
        @Override
        public void call()
        {
            System.out.println("this is mp3 call");
        }
    }
    Copy after login

    Implementation class 2

    public class Mp4Vedio implements VedioSPI
    {
        @Override
        public void call()
        {
           System.out.println("this is mp4 call");
        }
    }
    Copy after login

    In the source directory of the project Create the com.skywares.fw.juc.spi.VedioSPI file in the new META-INF/services/ directory.

    How to implement SpringBoots SPI mechanism

    Related tests

    public class VedioSPITest
    {
        public static void main(String[] args)
        {
            ServiceLoader<VedioSPI> serviceLoader =ServiceLoader.load(VedioSPI.class);
            serviceLoader.forEach(t->{
                t.call();
            });
        }
    }
    Copy after login

    Description: Java implements spi through ServiceLoader to find the tool classes provided by the service.

    Running results

    How to implement SpringBoots SPI mechanism

    Source code analysis

    The above is just a simple example to implement the built-in SPI function of java. The implementation principle is that ServiceLoader is a built-in Java tool class for finding service providing interfaces. It searches for service providing interfaces by calling the load() method, and finally traverses to access the implementation classes of the service providing interfaces one by one.

    How to implement SpringBoots SPI mechanism

    It can be found from the source code:

    • The ServiceLoader class itself implements the Iterable interface and implements the iterator method in it. The iterator method The method in the internal class LazyIterator is called in the implementation. After parsing the service provider interface file, the final result is placed in the Iterator and returned. Direct access to the service provider interface implementation class is not supported.

    • The corresponding files for all service provider interfaces are placed in the META-INF/services/ directory. The final type determines that the PREFIX directory cannot be changed.

    Although the idea of ​​the SPI mechanism provided by java is very good, it also has corresponding disadvantages. The details are as follows:

    • Java’s built-in methods can only be obtained through traversal

    • The service provider interface must be placed in META-INF/services/ Under contents.

    In view of the problems existing in java's SPI, Spring's SPI mechanism follows the idea of ​​SPI, but expands and optimizes it.

    Spring SPI

    Spring SPI follows the design idea of ​​Java SPI. Spring uses the spring.factories method to implement the SPI mechanism, which can provide the Spring framework without modifying the Spring source code. Scalability.

    Spring example

    Definition interface

    public interface DataBaseSPI
    {
       void getConnection();
    }
    Copy after login

    Related implementation

    #DB2实现
    public class DB2DataBase implements DataBaseSPI
    {
        @Override
        public void getConnection()
        {
            System.out.println("this database is db2");
        }
    }
    #Mysql实现
    public class MysqlDataBase implements DataBaseSPI
    {
        @Override
        public void getConnection()
        {
           System.out.println("this is mysql database");
        }
    }
    Copy after login

    1. In the META-INF directory of the project, add the spring.factories file

    How to implement SpringBoots SPI mechanism

    2. Fill in the relevant interface information, the content is as follows

    com.skywares.fw.juc.springspi.DataBaseSPI = com.skywares.fw .juc.springspi.DB2DataBase, com.skywares.fw.juc.springspi.MysqlDataBase

    Description Multiple implementations are separated by commas.

    Related test class

    public class SpringSPITest
    {
        public static void main(String[] args)
        {
             List<DataBaseSPI> dataBaseSPIs =SpringFactoriesLoader.loadFactories(DataBaseSPI.class, 
                     Thread.currentThread().getContextClassLoader());
             for(DataBaseSPI datBaseSPI:dataBaseSPIs){
                datBaseSPI.getConnection();
             }
        }
    }
    Copy after login

    Output results

    How to implement SpringBoots SPI mechanism

    We can see from the example that Spring uses spring.factories to implement SPI and java implementation SPI is very similar, but the relevant optimization of spring's spi method for java's spi is as follows:

    • Java SPI is a service providing interface corresponding to a configuration file, and the configuration file stores the current All implementation classes of the interface, multiple service provider interfaces correspond to multiple configuration files, all configurations are in the services directory;

    • Spring factories SPI is a spring.factories configuration file that stores multiple The interface and corresponding implementation class are configured with the fully qualified name of the interface as the key and the implementation class as the value. Multiple implementation classes are separated by commas. There is only one configuration file, spring.factories.

    So how does spring implement SpI by loading spring.factories? We can further analyze through the source code.

    Source code analysis

    How to implement SpringBoots SPI mechanism

    Description: loadFactoryNames parses the fully qualified name of the implementation class of the specified interface in the spring.factories file. The specific implementation is as follows:

    How to implement SpringBoots SPI mechanism

    Description: Get the file path of META-INF/spring.factories in all jar packages and return it as an enumeration value. Traverse the spring.factories file path, load and parse one by one, integrate the implementation class name of the factoryClass type, obtain the full class name of the implementation class, and then perform the instance operation of the class. The relevant source code is as follows:

    How to implement SpringBoots SPI mechanism

    Note: Instantiation implements corresponding initialization through reflection.

    The above is the detailed content of How to implement SpringBoot's SPI mechanism. For more information, please follow other related articles on the PHP Chinese website!

    Related labels:
    source:yisu.com
    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
    Popular Tutorials
    More>
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template