java spi

Java SPI (Service Provider Interface) is the mechanism to load services dynamically. We can implement Java SPI in our application by following the specific set of rules and load the services using the ServiceLoader class.

Java SPI(服务提供者接口)是动态加载服务的机制。 通过遵循特定的规则集,我们可以在我们的应用程序中实现Java SPI,并使用ServiceLoader类加载服务。



Java SPI组件 (Java SPI Components)

There are four components in the SPI implementation.

SPI实现中包含四个组件。

  1. Service Provider Interface: An interface or abstract class that defines the contract for the service provider implementation classes.服务提供者接口 :定义服务提供者实现类的协定的接口或抽象类。
  2. Service Providers: The implementation classes that actually provides the services.服务提供者 :实际提供服务的实现类。
  3. SPI Configuration File: A special file that provides the logic to look for the services implementations. The file name must be present in the META-INF/services directory. The file name should be exactly same as the service provider interface fully qualified name. Every line in the file have one implementation service class details, again the fully qualified name of the service provider class.SPI配置文件 :一个特殊的文件,提供查找服务实现的逻辑。 文件名必须存在于META-INF / services目录中。 文件名应与服务提供商接口标准名称完全相同。 文件中的每一行都有一个实现服务类详细信息,再次是服务提供者类的完全限定名称。
  4. ServiceLoader: The Java SPI main class that is used to load the services for a service provider interface. There are various utility methods in the ServiceLoader to get specific implementations, iterate through them, or reload the services again.ServiceLoader :Java SPI主类,用于为服务提供者接口加载服务。 ServiceLoader中有多种实用程序方法可用于获取特定的实现,对其进行迭代或重新加载服务。


Java服务提供者接口示例 (Java Service Provider Interfaces Examples)

The java.util.spi package provides a lot of service provider interfaces that can be implemented to provide services.

java.util.spi包提供了许多服务提供程序接口,可以将其实现以提供服务。

  1. ResourceBundleProvider, ResourceBundleControlProvider, and AbstractResourceBundleProvider: Service Provider interfaces and abstract class for Resource Bundle implementation classes.ResourceBundleProvider,ResourceBundleControlProvider和AbstractResourceBundleProvider:资源提供程序实现类的服务提供程序接口和抽象类。
  2. LocaleServiceProvider, CalendarDataProvider, CalendarNameProvider, CurrencyNameProvider, TimeZoneNameProvider, and LocaleNameProvider: for implementing Locale specific service providers.LocaleServiceProvider,CalendarDataProvider,CalendarNameProvider,CurrencyNameProvider,TimeZoneNameProvider和LocaleNameProvider:用于实现特定于区域设置的服务提供者。

Java SPI Interfaces List

Java SPI接口列表



Java SPI示例 (Java SPI Example)

Let’s create an implementation of SPI and load some services using the ServiceLoader class.

让我们创建SPI的实现,并使用ServiceLoader类加载一些服务。



1.服务提供商接口 (1. Service Provider Interface)

Let’s say we have a MessageServiceProvider interface that defines the contract for the service provider implementations.

假设我们有一个MessageServiceProvider接口,它定义了服务提供者实现的合同。

package com.journaldev.serviceproviders;public interface MessageServiceProvider {void sendMessage(String message);
}


2.服务提供商实施类 (2. Service Provider Implementation Classes)

We want to support email messages and push notification messages. So we will create two service provider implementations of MessageServiceProvider interface – EmailServiceProvider and PushNotificationServiceProvider.

我们希望支持电子邮件和推送通知消息。 因此,我们将创建MessageServiceProvider接口的两个服务提供程序实现-EmailServiceProvider和PushNotificationServiceProvider。

package com.journaldev.serviceproviders;public class EmailServiceProvider implements MessageServiceProvider {public void sendMessage(String message) {System.out.println("Sending Email with Message = "+message);}}
package com.journaldev.serviceproviders;public class PushNotificationServiceProvider implements MessageServiceProvider {public void sendMessage(String message) {System.out.println("Sending Push Notification with Message = "+message);}}


3.服务提供商配置文件 (3. Service Provider Configuration File)

The configuration file has to be created in the META-INF/services directory. Its name should be “com.journaldev.serviceproviders.MessageServiceProvider“. We will specify both the implementation classes in this file.

必须在META-INF / services目录中创建配置文件。 其名称应为“ com.journaldev.serviceproviders.MessageServiceProvider ”。 我们将在此文件中指定两个实现类。

com.journaldev.serviceproviders.EmailServiceProvider
com.journaldev.serviceproviders.PushNotificationServiceProvider


4.加载服务的ServiceLoader示例 (4. ServiceLoader Example to Load Services)

Finally, we have to load the services using the ServiceLoader class. Here is a simple test program showing its usage.

最后,我们必须使用ServiceLoader类加载服务。 这是一个显示其用法的简单测试程序。

package com.journaldev.test;import java.util.Optional;
import java.util.ServiceLoader;import com.journaldev.serviceproviders.MessageServiceProvider;public class ServiceLoaderTest {public static void main(String[] args) {ServiceLoader<MessageServiceProvider> serviceLoader = ServiceLoader.load(MessageServiceProvider.class);for (MessageServiceProvider service : serviceLoader) {service.sendMessage("Hello");}// using Java 8 Optional to get the first serviceOptional<MessageServiceProvider> firstService = serviceLoader.findFirst();if (firstService.isPresent()) {firstService.get().sendMessage("Hello Friend");}// using Java 8 forEach() methodserviceLoader.forEach((service) -> service.sendMessage("Have a Nice Day!"));// Total Number of Loaded ServicesSystem.out.println(serviceLoader.stream().count());}}

When we run the above program, we get the following output.

当我们运行上面的程序时,我们得到以下输出。

Sending Email with Message = Hello
Sending Push Notification with Message = Hello
Sending Email with Message = Hello Friend
Sending Email with Message = Have a Nice Day!
Sending Push Notification with Message = Have a Nice Day!
2

The below image shows our final project structure and SPI components.

下图显示了我们的最终项目结构和SPI组件。

Java SPI Example Project Structure

Java SPI示例项目结构



ServiceLoader重要方法 (ServiceLoader Important Methods)

Let’s look at the important methods of the ServiceLoader class.

让我们看一下ServiceLoader类的重要方法。

  • load(): The static method to load the services of a particular SPI.load():加载特定SPI服务的静态方法。
  • findFirst(): returns the first service available for this service provider.findFirst():返回可用于该服务提供者的第一个服务。
  • forEach(): useful to run some code for every service provider in this service loader instance.forEach() :在此服务加载器实例中为每个服务提供者运行一些代码很有用。
  • stream(): returns the stream of the service providers in this service loader.stream() :返回此服务加载器中服务提供者的流。
  • iterator(): returns an iterator of the service providers.iterator():返回服务提供者的迭代器 。
  • reload(): reloads the service providers. It’s useful when we change the service provider configurations on the fly and want to reload the services list.reload():重新加载服务提供商。 当我们即时更改服务提供商的配置并希望重新加载服务列表时,这很有用。


结论 (Conclusion)

Java SPI provides an easy way to dynamically configure and load the services in our application. However, it depends a lot on the service configuration file and any change in the file can break the application.

Java SPI提供了一种简单的方法来动态配置和加载应用程序中的服务。 但是,这在很大程度上取决于服务配置文件,并且文件中的任何更改都可能破坏应用程序。



参考资料 (References)

  • ServiceLoader API DocServiceLoader API文档


GitHub Repository.GitHub存储库中检出完整的项目。

翻译自: https://www.journaldev.com/31602/java-spi-service-provider-interface-and-serviceloader

java spi

java spi_Java SPI(服务提供商接口)和ServiceLoader相关推荐

  1. 交叉验证选择最佳参数_如何为您的公司选择最佳的身份验证即服务提供商

    交叉验证选择最佳参数 by Jeff Okawa 通过Jeff Okawa 如何为您的公司选择最佳的身份验证即服务提供商 (How to choose the best Authentication ...

  2. 音视频转码技术指南:国内主流云转码服务提供商对比测评

    摘要: 随着大量视频产生,怎样才能够高效精准地对视频进行云端转码和处理,来适配多终端展示需求和应对复杂的网络情况,是我们视频行业开发人员工作的重中之重.作为从业者,我们会经常接触各大云转码服务商,对音 ...

  3. sso 服务端配置_使用身份传播配置服务提供商启动的SSO

    sso 服务端配置 关于本系列 这个由三部分组成的系列文章"使用带有WebSphere Liberty的SAML 2.0进行跨域单点登录"介绍了在混合云环境中使用IBM®Cloud ...

  4. 大数据销售管理服务提供商InsideSales获得1亿美元融资

    专注于提高销售效率的大数据销售分析服务提供商InsideSales今日获得来自包括 SaleForce 在内的八家机构的 1 亿美金 C 轮融资,使其估值接近 10 亿美元. InsideSales ...

  5. 如何从管理IT服务提供商获得最大收益

    管理服务提供商(managed service provider,MSP)对你的IT服务的部分职能可能大有裨益.除了处理电子邮件主机或客户关系管理等特定领域外,将MSP作为IT组合的一部分,可以解放内 ...

  6. 服务提供商应该如何帮助企业保护数据安全

    本文讲的是 服务提供商应该如何帮助企业保护数据安全,大型.小型.公有.私有.政府.零售.B2B.非盈利组织. 黑客不关心被攻击企业的规模或业务.他们正在利用复杂的多矢量DDoS攻击袭击全球网络,试图获 ...

  7. 约三分之二的 DDoS 攻击指向通信服务提供商

    百度智能云 云生态狂欢季 热门云产品1折起>>>   据网络安全公司 Nexusguard 2018年第三季度的 DDoS 威胁报告,该季度有66.5%的 DDoS 攻击指向通信服务 ...

  8. 《2017 云计算评测报告》:带你了解 AWS、阿里云、腾讯云等八家云计算服务提供商的综合用户体验情况...

     报告电子版至听云官方博客下载:http://blog.tingyun.com/web/article/detail/1352 评测说明 评测目标:同一应用(网站)在不同云上的用户访问体验,以及对云资 ...

  9. 云服务提供商 | 等级保护测评报告

    文章目录 背景 云服务商 用户的需求 背景 自从2017年6月1日之后,等级保护越来越重视了.毕竟合规是要做的.不做的话哈哈. 我司的云平台刚刚做了等保,因为云平台里的用户也需要过等保,他们要过等保的 ...

最新文章

  1. ios基础篇(二十六)—— UITableViewCell的分组索引与标记
  2. HDU4259(简单群置换)
  3. Yet Another Walking Robot CodeForces - 1296C
  4. mysql数据库唯一性_在MySQL数据库中添加唯一性约束,范围可能吗?
  5. 我的docker随笔28:基于容器的升级方案实验
  6. Docker学习总结(19)——Google开源的容器集群管理系统Kubernetes介绍
  7. bzoj5194: [Usaco2018 Feb]Snow Boots
  8. (day 19 - 动态规划)剑指 Offer 42. 连续子数组的最大和
  9. 自己组装电脑配置清单 2021年组装电脑配置清单推荐
  10. 对LNode*与LinkLinst等价却不等用的理解
  11. 国美易卡取得长足发展,国美易卡NVIDIA深度学习
  12. android按键录制,安卓按键精灵怎么录制脚本
  13. 骨传导原理是什么?骨传导耳机对保护耳朵健康有帮助吗?
  14. 苹果手机怎么扩大内存_怎样扩大手机内存
  15. 求绝对值(调用函数)
  16. 如何查询土地规划用途_怎样使用GIS 技术来编制土地利用规划图
  17. iOS入门(二十)字典
  18. 用D触发器实现时钟分频
  19. 通讯rs232c语言编程,基于C51的RS232基本通信程序
  20. PhotoStage for mac幻灯片制作软件教程

热门文章

  1. 在VMware Workstation 9中安装Mac OS X 10.8 Mountain Lion
  2. 各浏览器的Hack写法【转】
  3. [转载] python函数isdisjoint方法_Python中的isdisjoint()函数
  4. [转载] python元组特点_python元组的优势有哪些
  5. 一个优质的Vue组件库应该遵循什么样的设计原则
  6. day00 -----博客作业1
  7. 如何解决js地址栏中传递中文乱码的问题
  8. 快速幂算法(矩阵快速幂还不是很会。。日后会更新)
  9. 项目需求:基于微信平台的拼团活动系统
  10. 【原创】使用Ultra Librarian为Altium Designer 09生成元器件库