SpringBoot+SPI機(jī)制實(shí)現(xiàn)可插拔組件
什么是Java的SPI
Java SPI(Service Provider Interface)是一種服務(wù)提供界面,它是Java提供的一種服務(wù)發(fā)現(xiàn)和加載機(jī)制,允許開發(fā)者為接口定義多種實(shí)現(xiàn),并在運(yùn)行時(shí)動(dòng)態(tài)地發(fā)現(xiàn)和加載這些實(shí)現(xiàn)。
Java SPI機(jī)制的核心在于它提供了一種方式,使得服務(wù)提供者可以根據(jù)SPI的約定,為某個(gè)接口提供具體的實(shí)現(xiàn)類。這些實(shí)現(xiàn)類被放置在特定的位置,如META-INF/services目錄下,并通過配置文件指定。當(dāng)需要使用這些服務(wù)時(shí),Java運(yùn)行時(shí)環(huán)境能夠自動(dòng)掃描這些目錄,找到并加載相應(yīng)的實(shí)現(xiàn)類,從而實(shí)現(xiàn)服務(wù)的動(dòng)態(tài)發(fā)現(xiàn)和加載。
Java SPI的主要用途包括:
- 服務(wù)提供者可以在不修改業(yè)務(wù)代碼的情況下,為框架或庫提供擴(kuò)展點(diǎn)。
- 允許在運(yùn)行時(shí)動(dòng)態(tài)地插入或更換組件實(shí)現(xiàn),鼓勵(lì)松耦合的設(shè)計(jì)原則。
- 允許第三方擴(kuò)展和替換核心庫中的組件,豐富了Java生態(tài),為開發(fā)者提供了極大的靈活性。
在Java中,SPI被廣泛應(yīng)用于各種框架和庫的擴(kuò)展,如Servlet容器初始化、類型轉(zhuǎn)換、日志記錄等場景。通過SPI機(jī)制,Java應(yīng)用程序可以在不修改業(yè)務(wù)代碼的情況下,輕松地集成和使用第三方提供的服務(wù)實(shí)現(xiàn),從而提高了軟件的可擴(kuò)展性和可維護(hù)性
SPI和API的區(qū)別
SPI和API的主要區(qū)別在于它們的定義方式、調(diào)用方式、靈活性、依賴關(guān)系以及用途。
- 定義方式: API是由開發(fā)者主動(dòng)編寫并公開給其他開發(fā)者使用的,而SPI是由框架或庫提供方定義的接口,供第三方開發(fā)者實(shí)現(xiàn)。
- 調(diào)用方式: API通過直接調(diào)用接口的方法來使用功能,而SPI是通過配置文件來指定具體的實(shí)現(xiàn)類,然后由框架或庫自動(dòng)加載和調(diào)用。
- 靈活性: API的實(shí)現(xiàn)類必須在編譯時(shí)就確定,無法動(dòng)態(tài)替換;而SPI的實(shí)現(xiàn)類可以在運(yùn)行時(shí)根據(jù)配置文件的內(nèi)容進(jìn)行動(dòng)態(tài)加載和替換。
- 依賴關(guān)系: API是被調(diào)用方依賴的,即應(yīng)用程序需要引入API所在的庫才能使用其功能;而SPI是調(diào)用方依賴的,即框架或庫需要引入第三方實(shí)現(xiàn)類的庫才能加載和調(diào)用。
- 用途: API通常用于描述庫、框架、操作系統(tǒng)、服務(wù)等對外提供的編程接口,開發(fā)者通過API調(diào)用相應(yīng)的功能來實(shí)現(xiàn)自己的應(yīng)用程序。而SPI定義了一種插件式的架構(gòu),允許開發(fā)者定義接口,并通過服務(wù)提供者來提供不同的實(shí)現(xiàn),主要目的是允許系統(tǒng)在運(yùn)行時(shí)發(fā)現(xiàn)和加載具體的服務(wù)提供者,從而實(shí)現(xiàn)動(dòng)態(tài)擴(kuò)展和替換功能的能力。
綜上所述,API是一種規(guī)范,描述了如何與一個(gè)組件進(jìn)行交互;而SPI則是一種機(jī)制,用于動(dòng)態(tài)地發(fā)現(xiàn)和加載實(shí)現(xiàn)了特定接口的組件。
實(shí)現(xiàn)過程
0.目錄結(jié)構(gòu)
sa-auth 父工程
-- sa-auth-bus 業(yè)務(wù)工程
-- sa-auth-plugin 定義SPI接口的工程
-- sa-auth-plugin-ldap 模擬第三方庫的實(shí)現(xiàn)工程
1.idea創(chuàng)建名為sa-auth 的pom 項(xiàng)目,pom 如下
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.16.RELEASE</version>
</parent>
<groupId>com.vijay</groupId>
<artifactId>cs-auth</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>cs-auth</name>
<packaging>pom</packaging>
<description>cs-auth</description>
<properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.compilerVersion>1.8</maven.compiler.compilerVersion>
</properties>
<modules>
<module>cs-auth-plugin</module>
<module>cs-auth-bus</module>
<module>cs-auth-plugin-ldap</module>
</modules>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
</dependency>
<dependency>
<groupId>com.vijay</groupId>
<artifactId>cs-auth-plugin</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
</dependencies>
</dependencyManagement>
</project>
2.然后創(chuàng)建sa-auth-plugin,pom 如下
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.vijay</groupId>
<artifactId>cs-auth</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<artifactId>cs-auth-plugin</artifactId>
<name>cs-auth-plugin</name>
<description>cs-auth-plugin</description>
</project>
3.sa-auth-bus,pom 如下
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.vijay</groupId>
<artifactId>cs-auth</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<artifactId>cs-auth-bus</artifactId>
<name>cs-auth-bus</name>
<description>cs-auth-bus</description>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.vijay</groupId>
<artifactId>cs-auth-plugin</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.1.1.RELEASE</version>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
4.sa-auth-plugin-ldap,pom如下
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.vijay</groupId>
<artifactId>cs-auth</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<artifactId>cs-auth-plugin-ldap</artifactId>
<name>cs-auth-plugin</name>
<description>cs-auth-plugin-ldap</description>
<dependencies>
<dependency>
<groupId>com.vijay</groupId>
<artifactId>cs-auth-plugin</artifactId>
</dependency>
</dependencies>
</project>
5.創(chuàng)建好的項(xiàng)目結(jié)構(gòu)如下

6.打開sa-auth-plugin,定義SPI接口
package com.vijay.csauthplugin.service;
/**
* 插件SPI接口
*
* @author vijay
*/
publicinterface AuthPluginService {
/**
* 登錄認(rèn)證
*
* @param userName 用戶名
* @param password 密碼
* @return 認(rèn)證結(jié)果
*/
boolean login(String userName, String password);
/**
* AuthPluginService Name which for conveniently find AuthPluginService instance.
*
* @return AuthServiceName mark a AuthPluginService instance.
*/
String getAuthServiceName();
}

7.cs-auth-plugin-ldap 中實(shí)現(xiàn)SPI的接口并且打成jar包,模擬外部提供的插件jar包
1.實(shí)現(xiàn)引入的cs-auth-plug包的SPI接口 package com.vijay.csauthplugin.ldap;
package com.vijay.csauthplugin.ldap;
import com.vijay.csauthplugin.service.AuthPluginService;
/**
* @author vijay
*/
publicclass LdapProviderImpl implements AuthPluginService {
@Override
public boolean login(String userName, String password) {
return"vijay".equals(userName) && "123456".equals(password);
}
@Override
public String getAuthServiceName() {
return"LdapProvider";
}
}
2.resources目錄下創(chuàng)建META-INF/services目錄,并在目錄下創(chuàng)建一個(gè)名為SPI接口類的全路徑限定名com.vijay.csauthplugin.service.AuthPluginService的文件,文件中寫入LdapProviderImpl 實(shí)現(xiàn)類的全路徑限定名com.vijay.csauthplugin.ldap.LdapProviderImpl

3.cs-auth-plugin-ldap打包成jar包
8.打開cs-auth-plugin-bus
1.項(xiàng)目下創(chuàng)建plugin包,添加一個(gè)插件的默認(rèn)實(shí)現(xiàn)DefaultProviderImpl
package com.vijay.bus.plugin;
import com.vijay.csauthplugin.service.AuthPluginService;
/**
* 默認(rèn)插件實(shí)現(xiàn)
*
* @author vijay
*/
publicclass DefaultProviderImpl implements AuthPluginService {
@Override
public boolean login(String userName, String password) {
return"vijay".equals(userName) && "123456".equals(password);
}
@Override
public String getAuthServiceName() {
return"DefaultProvider";
}
}
2.resources目錄下創(chuàng)建META-INF/services目錄并在目錄下創(chuàng)建一個(gè)名為SPI接口類全路徑限定名的文件com.vijay.csauthplugin.service.AuthPluginService,文件內(nèi)容為DefaultProviderImpl全路徑限定名com.vijay.bus.plugin.DefaultProviderImpl.自定義類加載器
package com.vijay.bus.plugin;
import java.net.URL;
import java.net.URLClassLoader;
/**
* 自定義類加載器
*
* @author vijay
*/
publicclass PluginClassLoader extends URLClassLoader {
public PluginClassLoader(URL[] urls) {
super(urls);
}
/**
* @param url 路徑
*/
public void addzURL(URL url) {
super.addURL(url);
}
}
4.定義一個(gè)加載外部jar包的類
package com.vijay.bus.plugin;
import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
/**
* 加載指定目錄jar包
* @author vijay
*/
publicclass ExternalJarLoader {
/**
* 加載外部jia包
*
* @param externalDirPath jar包目錄
*/
public static void loadExternalJars(String externalDirPath) {
File dir = new File(externalDirPath);
if (!dir.exists() || !dir.isDirectory()) {
thrownew IllegalArgumentException("Invalid directory path");
}
List<URL> urls = new ArrayList<>();
File[] listFiles = dir.listFiles();
if (Objects.nonNull(listFiles) && listFiles.length > 0) {
ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
try {
for (File file : listFiles) {
if (file.getName().endsWith(".jar")) {
urls.add(file.toURI().toURL());
}
}
PluginClassLoader customClassLoader = new PluginClassLoader(urls.toArray(new URL[0]));
Thread.currentThread().setContextClassLoader(customClassLoader);
} catch (Exception e) {
e.printStackTrace();
Thread.currentThread().setContextClassLoader(contextClassLoader);
}
}
}
}
5.啟動(dòng)類中添加類加載器
package com.vijay.bus;
import com.vijay.bus.plugin.ExternalJarLoader;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* @author vijay
*/
@SpringBootApplication
publicclass CsAuthBusApplication {
public static void main(String[] args) {
String jarPath="/Users/vijay/Downloads/build/plugin";
ExternalJarLoader.loadExternalJars(jarPath);
SpringApplication.run(CsAuthBusApplication.class, args);
}
}
6.創(chuàng)建插件提供者類PluginProvider,提供實(shí)現(xiàn)類供springboot注入
package com.vijay.bus.plugin;
import com.vijay.csauthplugin.service.AuthPluginService;
import java.util.ServiceLoader;
/**
* 插件提供者
*
* @author vijay
*/
publicclass PluginProvider {
/**
* 提供一個(gè)插件供注入(默認(rèn)返回外部目錄的插件,外部目錄沒有插件時(shí)返回默認(rèn)插件)
*
* @return 具體的插件實(shí)現(xiàn)
*/
public static AuthPluginService getAuthPluginService() {
ServiceLoader<AuthPluginService> defaultLoad = ServiceLoader.load(AuthPluginService.class);
AuthPluginService plugin = null;
for (AuthPluginService authPluginService : defaultLoad) {
if (authPluginService instanceof DefaultProviderImpl) {
plugin = authPluginService;
} else {
return authPluginService;
}
}
return plugin;
}
}
7.項(xiàng)目下創(chuàng)建conf包,注入實(shí)現(xiàn)類到springboot
package com.vijay.bus.conf;
import com.vijay.bus.plugin.PluginProvider;
import com.vijay.csauthplugin.service.AuthPluginService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author vijay
*/
@Configuration
publicclass PluginConfig {
@Bean
public AuthPluginService authPluginService() {
return PluginProvider.getAuthPluginService();
}
}
8.項(xiàng)目下創(chuàng)建controller包,定義controller接口,調(diào)用測試
package com.vijay.bus.controller;
import com.vijay.csauthplugin.service.AuthPluginService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
/**
* @author vijay
*/
@RestController
publicclass TestController {
@Resource
private AuthPluginService authPluginService;
@GetMapping("test")
public Object test() {
returnnew HashMap() {{
put("name", authPluginService.getAuthServiceName());
put("login", authPluginService.login("vijay", "123456"));
}};
}
}
完整結(jié)構(gòu)

9.請求接口,測試實(shí)現(xiàn)

此時(shí)返回為默認(rèn)實(shí)現(xiàn),把cs-auth-plugin-ldap項(xiàng)目模擬的第三方包放到外部jar包加載目錄,重新啟動(dòng)項(xiàng)目后發(fā)起請求

實(shí)現(xiàn)已經(jīng)是模擬的jar的實(shí)現(xiàn)
到此這篇關(guān)于SpringBoot+SPI機(jī)制實(shí)現(xiàn)可插拔組件的文章就介紹到這了,更多相關(guān)SpringBoot SPI可插拔組件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
java 裝飾模式(Decorator Pattern)詳解
這篇文章主要介紹了java 裝飾模式(Decorator Pattern)詳解的相關(guān)資料,需要的朋友可以參考下2016-10-10
基于Java在netty中實(shí)現(xiàn)線程和CPU綁定
這篇文章主要介紹了基于Java在netty中實(shí)現(xiàn)線程和CPU綁定,文章圍繞主題的相關(guān)內(nèi)容展開詳細(xì)介紹,具有一定的參考價(jià)值,需要的小伙伴可以參考一下2022-05-05
java中hasNextInt判斷后無限循環(huán)輸出else項(xiàng)的解決方法
這篇文章主要介紹了java中hasNextInt判斷后無限循環(huán)輸出else項(xiàng)的解決方法的相關(guān)資料,需要的朋友可以參考下2016-10-10
SpringBoot自動(dòng)配置的實(shí)現(xiàn)原理
這篇文章主要介紹了詳解SpringBoot自動(dòng)配置原理,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2019-01-01
Spring?Boot?3中一套可以直接用于生產(chǎn)環(huán)境的Log4J2日志配置詳解
Log4J2是Apache Log4j的升級版,參考了logback的一些優(yōu)秀的設(shè)計(jì),并且修復(fù)了一些問題,因此帶來了一些重大的提升,這篇文章主要介紹了Spring?Boot?3中一套可以直接用于生產(chǎn)環(huán)境的Log4J2日志配置,需要的朋友可以參考下2023-12-12

