ServiceLoaderUtil

ServiceLoaderUtil

Introduction

SPI (Service Provider Interface) is a service discovery mechanism that automatically loads classes defined in files found under the META-INF/services folder in the ClassPath.

For more information: https://www.jianshu.com/p/3a3edbcd8f24

Usage

Define an interface:

package cn.hutool.test.spi;

public interface SPIService {
    void execute();
}

There are two implementations:

package cn.hutool.test.spi;

public class SpiImpl1 implements SPIService{
    public void execute() {
        Console.log("SpiImpl1.execute()");
    }
}
package cn.hutool.test.spi;

public class SpiImpl2 implements SPIService{
    public void execute() {
        Console.log("SpiImpl2.execute()");
    }
}

Then create a file called cn.hutool.test.spi.SPIService in the META-INF/services folder of the classpath, with the following content:

cn.hutool.test.spi.SpiImpl1
cn.hutool.test.spi.SpiImpl2

Load the first available service implementation that is defined by the user for multiple interface implementation classes. This method is commonly used for automatically identifying and loading multiple implementations of the same interface, by checking whether the jar is included and automatically finding the implementation class.

SPIService service = ServiceLoaderUtil.loadFirstAvailable(SPIService.class);
service.execute();