Developing a Service Provider using Java API(Service Provider Interface)

微软Azure Linux开源云操作系统深度解析与实战部署 Linux操作系统作为开源技术的核心基础,通过内核调度和资源管理实现高效计算环境。其模块化架构支持灵活的定制优化,在云计算时代展现出重要技术价值。云原生场景下,针对特定云平台深度优化的Linux发行版能够显著提升性能和安全特性。Azure Linux作为微软基于Fedora构建的开源发行版,采用覆盖层系统实现Azure云环境专属优化,在安全加固和性能调优方面具有独特优势。该操作系统通过深度集成Azure托管服务标识和优化虚拟化驱动,为容器化工作负载和微服务架构提供理想的运行平台,自然契合现代云原生应用部署需 阅读详情

这篇关于SPI的文章是在blogspot上面,被ZF给强奸了,大多数人访问不了,就贴在这里,比较好懂。

From ServiceLoader javadoc: A service is a well-known set of interfaces and classes. A service provider is a specific implementation of a service. The classes in a provider typically implement the interfaces and subclass the classes defined in the service itself.

Since JDK 6, a simple service-provider loading facility is implemented. As is suggested it is simple, you cannot understand that implementation as a complex system for implementing plugins for your application, but can help you in many situations where you want  implementations of a service could be discovered by other module automatically.

What I really like about using JDK Services is that your services do not have any dependency to any class. Moreover for registering a new implementation of a service, you just have to put jar file into classpath and nothing more.

Now I will explain the service we are going to implement, and then I will show you how to code it.

We want to implement a system that depending on kind of structured input (comma-separated value, tab-separated value, ...) returns a String[] of each value; so for example you can receive input a,b,c,dor 1<tab>2<tab>3<tab>4 and the system should return an array with  [a, b, c, d] or [1, 2, 3, 4].

So our system will have three Java projects.

One defining service contract (an interface) and, because of teaching purpose, a main class where internet media type, for example text/csv, is received with input data. Then using a factory class that I have created, it will ask which registered service can transform input to String[].

And two projects each one implementing a service following defined contract, one for comma-separated values and another one for tab-separated values.

Let's see the code:

Main project (reader) is composed by an interface, a main class and a factory class.

The most important part is Decode interface which defines service contract.

public interface Decode {

 boolean isEncodingNameSupported(String encodingName);
 String[] getContent(String data);
 
}
Two operations are defined, one that returns if service supports given input, and another that transforms data to  String[] .

DecodeFactory  class is responsible for finding an implementation service that supports required encoding. In fact, this class encapsulates  java.util.ServiceLoader  calls.  ServiceLoader  class is in charge of load registered services.

public class DecodeFactory {

 private static ServiceLoader decodeSetLoader = ServiceLoader.load(Decode.class);
 
 public static Decode getDecoder(String encodingName) throws UnsupportedEncodingException {
  
  for (Decode decode : decodeSetLoader) {
   if(decode.isEncodingNameSupported(encodingName)) {
    return decode;
   }
  }

  throw new UnsupportedEncodingException();
 }
}
At line 3 we are loading all services that are registered in classpath. At line 7 we only iterate through all services asking if given encoding name is supported.

And finally main class.

public class App {
 
 public static void main(String[] args) throws UnsupportedEncodingException {
  
  String encodeName = args[0];
  String data = args[1];
  
  Decode decoder = DecodeFactory.getDecoder(encodeName);
  System.out.println(Arrays.toString(decoder.getContent(data)));
  
 }
}
And now if you run this class with  java -jar reader.jar "text/cvs" "a, b, c, d" , an UnsupportedEncodingException  will be thrown. Now we are going to implement our first service. Note that reader project will not be modified nor recompiled.

First service we are going to implement is one that can support  comma-separated values  encoding. Only one class and one file are important.

CSV  class is an implementation of  Decode  interface and transforms comma-separated values.

public class CSVDecoder implements Decode {

 private static final String DELIMITER = Character.toString(DecimalFormatSymbols.getInstance().getPatternSeparator());
 
 public boolean isEncodingNameSupported(String encodingName) {
  return "text/csv".equalsIgnoreCase(encodingName.trim());
 }

 public String[] getContent(String data) {
  
  List values = new LinkedList();
  
  StringTokenizer parser = new StringTokenizer(data, DELIMITER);
  
  while(parser.hasMoreTokens()) {
   values.add(parser.nextToken());
  }
  
  return values.toArray(new String[values.size()]);
  
 }

}
As you can see a simple  StringTokenizer  class. Only take care that this class is  Locale  sensitive, countries where comma (,) is used as decimal delimiter, separation character is semicolon (;).

And next important file is a file that is placed into  META-INF.  This file contains a pointer to service implementation class.

This file should be in  META-INF/services  and should be called as interface full qualified name. In this case  org.alexsotob.reader.Decode . And its content should be service implementation full qualified name.

org.alexsotob.reader.csv.CSVDecoder #Comma-separated value decode.

And now you can package this project, and you can reexecute  reader project but with generated  jar( csv.jar) into  classpath. And now output will be an array with  a, b, c and d characters instead of unsupported exception.

See that reader project has not been modified and its behaviour has been changed. Now you can develop new implementations for decoding new inputs, and you should only take care of copying them into classpath.

Only take care that all services should have a default constructor with no arguments.

And for those who use  Spring Framework,  Services are also supported through three different FactoryBeans,  ServiceFactoryBean,  ServiceListFactoryBean,  ServiceLoaderFactoryBean.

As I have noted at start of this post,  JDK services is a simple (yet powerful) solution if you need to create a simple plugins system. In my case it has been enough with  JDK services, and I have never required more complex structure; but in case you are thinking about a complete plugin solution you can use  JPF that offers a solution like  Eclipse plugins, or even  OSGI.

I wish you have found this post useful and now you know (if you didn't know yet), an easy solution to develop modules that are plugged and play.



原文链接: http://alexsotob.blogspot.com/2011/11/en-ti-puedo-ver-la-libertad-tu-me-haces.html




Service Provider Interface详解 (SPI) 1.介绍 熟悉JDBC的同学都知道,在jdbc4.0之前,在使用DriverManager获取DB连接之前,我们总是需要显示的实例化DB驱动。比如,对mysql,典型的代码如下: Connection conn = null; Statement stmt = null; try{ // 注册 JDBC driver Class.forName("com.mysql.jdbc... 阅读详情

相关推荐

实测对比:DeepSeek、豆包、千问三大AI模型生成测试用例谁更强?(附完整代码)

本文通过实测对比了DeepSeek、豆包、千问三大AI模型在生成测试用例方面的表现。文章提供了完整的Python代码实现,详细分析了各模型在用例完整性、准确性、边界覆盖及幻觉控制等维度的差异,并分享了工程化集成与多模型融合等优化策略,旨在帮助测试团队选择合适工具以提升工作效率。

ik6789012的博客 993

Spring Bean基础

为什么要先掌握 Spring Bean 的基础知识?我们知道 Spring 框架提供的一个最重要也是最核心的能力就是管理 Bean 实例。Spring框架的核心是IoC(Inversion of Control)容器,而Bean是IoC容器的基本构建块。理解Spring Bean的概念和使用方式是学习和使用Spring框架的第一步。Spring框架通过依赖注入实现了对象之间的解耦。

MarkusZhang的博客 1361

CRaxsRat v7.6 安装与使用教程(附工具下载)

摘要:本文介绍远程管理工具CRaxsRat v7.6的合法应用与基本操作,强调仅限授权环境使用。该工具支持多客户端管理、TLS加密及文件/进程控制等功能,适用于内网维护与安全测试。安装需Windows 10/11系统及.NET 4.8,步骤包括解压运行、配置监听端口及生成客户端。文中提醒防火墙设置与杀软误报问题,并重申禁止非法用途,建议在虚拟机或隔离环境学习使用。

lzj781210的博客 3827

android spi 简书,Service Provider Interface详解 (SPI)

1.介绍熟悉JDBC的同学都知道,在jdbc4.0之前,在使用DriverManager获取DB连接之前,我们总是需要显示的实例化DB驱动。比如,对mysql,典型的代码如下:Connection conn = null;Statement stmt = null;try{// 注册 JDBC driverClass.forName("com.mysql.jdbc.Driver");// 打开连接...

weixin_42364301的博客 466

Python爬虫实战:逆向解析央视频加密参数(附完整代码)

本文详细解析了央视频加密体系的技术实现,通过Python逆向工程实战演示如何解密动态密钥、AES加密和自定义哈希算法等核心组件。文章提供完整代码示例,涵盖GUID生成、参数构造和异步请求处理,帮助开发者掌握现代视频平台的反爬机制破解方法。

weixin_42532473的博客 1162

ABAP代码检查(Code Review)

1、SLIN 扩展程序检查 也可通过(SE38工具栏->检查-扩展程序检查) 进入 2、ATC 检查 通过<SE38菜单栏-检查-ABAP测试主控室> 或事物代码SCI, 支持自定义检查变式 SCI可以配置检查变式满足特殊需求,配置对象集用于批量检查 3、通过ABAP测试主控室实现统一管理,定期检查作业和监控功能(事务代码ATC) 参考 SLIN...

u012232542的博客 6093

Android组件化工具-SPI

SPI: service provider interface,使用接口、配置文件和策略模式,实现了解耦、模块化和组件化。 总结一下吧,SPI可以更好的实现组件化,结合AUtoService和ServiceLoader来实现,很方便。当然也可以自己开发一个sdk,把SPIUtils放进去,就可以更方便的使用了。

star_nwe的博客 377

如何实现SOLIDWORKS阵列的“智能变更”?

有时,我们在设计一个零件时,零件上有一排阵列孔,同时零件有不同的长度,我们又希望可以做到零件长度改变时,这排孔可以按长度等距增减孔阵列的个数;或是零件长度加长或缩短时,这排孔保持个数不变,按零件长度增减孔距。 那具体要怎么做呢?接下来,我们一起来看看怎么用SOLIDWORKS中简单的操作来实现这两种智能的变更: 零件长度加长或缩短时,这排孔要按长度等距增减孔阵列的个数。 零件长度加长或缩短时,这排孔保持个数不变,按零件长度增减孔距。 那接下来,我们一起来看看怎么用简单的操作来实现这两种智能的

SOLIDWORKS艾金米 2100

Java中的SPI(Service Provider Interface)介绍及示例(转)

一个服务(service)通常指的是已知的接口或者抽象类,服务提供方就是对这个接口或者抽象类的实现,然后按spi标准存放到资源路径META-INF/services目录下,文件的命名为该服务接口的全限定名。如有一个服务接口com.test.Service,其服务实现类为com.test.ChildService,那此时需要在META-INF/services中放置文件com.test.Servic...

weixin_33906657的博客 829

数据分析案例-2024 年全电动汽车数据集可视化分析

本数据集来源于Kaggle,原始数据集共有177866条数据,17个变量。该数据集显示了目前通过华盛顿州许可部 (DOL) 注册的电池电动汽车 (BEV) 和插电式混合动力电动汽车 (PHEV)。电池电动汽车 (BEV) 是一种全电动汽车,使用一个或多个电池来存储电能,为电机提供动力,并通过将车辆插入电源进行充电。插电式混合动力汽车 (PHEV) 是一种使用一个或多个电池为电动机提供动力的车辆;使用另一种燃料,例如汽油或柴油,为内燃机或其他推进源提供动力;并通过将车辆插入电源来充电。

m0_64336780的博客 1万+

Python解答蓝桥杯省赛真题之从入门到真题

搜了很多历年蓝桥杯真题解答,大多都是Java,C++,C这些语言编写的代码解析。Python解析的几乎,甚至可以说没有。而当下Python又这么火热,蓝桥杯也出了Python组,所以打算写一个Python解答蓝桥杯真题的博客,供大家参考,也在这过程中和大家一起交流。

李波的blog,一名喜欢编程和分享技术的研究僧~ 10万+

JAVA SPI(Service Provider Interface)原理、设计及源码解析(其一)

背景团队内部轮流技术分享,其他人都是分享源码,我每次都是设计和架构,感觉自己太特立独行。这次我要合群点,分享点源码。概念Service Provider Interfac...

xiexiaojing的博客 695

把入库交货单的 GOS 附件自动带进审批 Work Item:用 SOFM 对象打通 SAP Workflow 附件链路

本文介绍了一种在SAP ECC系统中将入库交货单的GOS附件自动附加到Workflow审批项中的解决方案。通过使用BOR对象引用列表和SOFM业务对象,审批人可直接在Work Item中查看附件,无需返回原单据界面。文章详细阐述了从BUS2015业务对象获取附件连接、转换LOIO_ID为SOFM对象引用,并将附件列表绑定到User Decision步骤的具体实现方法。该方案适用于经典SAP Business Workflow+BOR架构,核心ABAP代码可直接复用,有效解决了审批流程中的附件可见性问题。

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 258

Android 动态服务SPI的实现

Android 动态服务SPI的实现 声明:此处所谓的SPI是指Service Provider Interfaces,属于Java中动态加载Service的一项技术。 而非硬件编程中的SPI,那是Serial Peripheral Interface。 本文参照了元亨利贞o这位博主的博客,表示感谢。一、概念SPI即Service Provider Interfaces。Java的接口

冰路梦 2594

Statistics and Machine Learning Toolbox

Statistics and Machine Learning Toolbox(带书签),MATLAB统计学习工具

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

Android中SPI的使用

SPI全称是Service Provider Interface,服务提供方接口,服务通常是指一个接口或者一个抽象类,服务提供方是对这个接口或者抽象类的具体实现,由第三方来实现接口提供具体的服务。SPI提供了一种动态的对应用程序进行扩展的机制,通常用作框架服务的拓展或者可替换的服务组件,但是在Android中并没有广泛的使用。

王三的专栏 9705

Java中的SPI(Service Provider Interface)介绍及示例

一个服务(service)通常指的是已知的接口或者抽象类,服务提供方就是对这个接口或者抽象类的实现,然后按spi标准存放到资源路径META-INF/services目录下,文件的命名为该服务接口的全限定名。如有一个服务接口com.test.Service,其服务实现类为com.test.ChildService,那此时需要在META-INF/services中放置文件com.test.Serv...

Bluer的博客 222

SpringFactoriesLoader ServiceLoader区别

两者实现的功能很类似,不过 Spring 提供的功能更灵活一些。 IoC 并不仅限于解决模块内类与类之间的依赖耦合问题,其同样适用于模块与模块之间。OSGi 一直致力于这方面的工作。但其实 Java 和 Spring 都提供了对 IoC 的支持。 Java Service Loader Java 本身提供了一种很简便的方式来支持 IoC,它通过使用 [Service Loader] (htt...

varyall的专栏 793

阿里P7大牛亲自讲解!首发10万字Android开发实战文档,成功入职阿里

前言 下面的题目都是楼主在Android交流群大家在面试字节跳动时遇到的,如果大家有好的题目或者好的见解欢迎分享,楼主将长期维护此帖。 参考解析:郭霖、鸿洋、玉刚、极客时间、腾讯课堂… 内容特点:条理清晰,含图像化表示更加易懂。 内容概要:包括 Handler、Activity相关、Fragment、service、布局优化、AsyncTask相关 、Android 事件分发机制、 Binder、Android 高级必备 :AMS,WMS,PMS、Glide、 Android 组件化与插件化等面试题和技术栈

dswl88888的博客 611

Dao 的 Interface 和 Service 的 Interface

之前写 Spring MVC 时,傻乎乎的。由于不懂 Spring 是怎么进行注入的。以为只能靠 @Autowired,依赖 Interface 注入。其实 @Autowired 主要是根据类型进行注入。但是一旦在@Transactional 注解下,使用 Proxy,就要 Interface(这部分我到现在还不太懂… )这篇讲到了 Spring Proxy http://stackoverflow

ginkov的博客 3306

Java ServiceLoader与Spring工厂加载器

现在Spring boot来到了Jar世界,原来它是管理war世界的王者,所以,他也很可能带来了Jar打包规则的改变。Jar世界从OSGI到Java Service Loader以及Java 9的模块化,折腾了很长时间,现在看看Spring是如何折腾Jar包的动态加载的: 控制反转IOC不仅可以在类级别进行,而且可以在模块级别进行,虽然OSGi技术已经存世了很长时间了,但是,在Java中也可以像在...

乔志勇笔记 2158

Java中的SPI(Service Provider Interface)

SPI(Service Provider Interface),一个Java内置的标准,允许不同的开发者去实现某个特定的服务。 A service is a well-known set of interfaces and (usually abstract) classes. A service provider is a specific implementation of a serv

baohuan_love的专栏 1271

SPI(service provider interface 服务提供者接口)

SPI 平时写代码一般不会用到,但是到了做一些基础组件开发或者是中间件开发的时候,SPI 是一个必须要掌握的知识点...

wenniuwuren 3142

java做一个客房管理系统定制_Java实现酒店客房管理系统

本文实例为大家分享了Java实现酒店客房管理系统的具体代码,供大家参考,具体内容如下LoginFrame.javapackage loginManage;import java.awt.Color;import java.awt.EventQueue;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;imp...

weixin_39897887的博客 340

注解和反射

加上这个注解就是一个自定义注解了。

2203_75380029的博客 188

MQ工作模式

RabbitMQ 的工作模式,本质是。

2401_88415955的博客 192
上一篇: Annotation学习入门的几篇文章
下一篇: Ubuntu64位机上快速搭建ApacheMySQLPHP环境
冯立彬
冯立彬 优质创作者: 编程框架技术领域 优质创作者: 编程框架技术领域
博客等级 码龄21年 5458粉丝 593原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址