java-spi编程实践(Service Provider Interface+maven)

亦凉 2023-07-22 15:24 102阅读 0赞

背景

在研究java注解处理器的过程中,涉及到了spi机制的理解,本wiki将进行一下实践。

spi机制

spi机制的目标:实现接口与实现的解耦。
spi机制在开源项目中的应用:

  • spring中大量使用(ioc的过程会自动选取一个实现)
  • 数据库驱动加载
  • dubbo等等

简单的理解:spi技术就是jdk提供的一种callback技术(通过ServiceLoader类),大家都按照这个规范走,jdk自然会老老实实干活
在这里插入图片描述

在后续的博客中将对不同的框架进行调研并加以说明。

spi简易demo

创建一个maven项目

在这里插入图片描述
pom文件如下

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <modelVersion>4.0.0</modelVersion>
  6. <groupId>com.mine</groupId>
  7. <artifactId>spi-demo</artifactId>
  8. <version>1.0-SNAPSHOT</version>
  9. <properties>
  10. <java.version>1.8</java.version>
  11. <mapstruct.version>1.3.1.Final</mapstruct.version>
  12. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  13. </properties>
  14. <build>
  15. <plugins>
  16. <plugin>
  17. <artifactId>maven-compiler-plugin</artifactId>
  18. <version>2.5.1</version>
  19. <configuration>
  20. <source>1.8</source>
  21. <target>1.8</target>
  22. <compilerArgument>-proc:none</compilerArgument>
  23. </configuration>
  24. </plugin>
  25. </plugins>
  26. </build>
  27. </project>

创建普通的接口和实现

DemoInterface.java

  1. package com.mine;
  2. public interface DemoInterface {
  3. void myTest();
  4. }

DemoInterfaceImpl.java

  1. package com.mine;
  2. public class DemoInterfaceImpl implements DemoInterface {
  3. @Override
  4. public void myTest() {
  5. System.out.println("haha");
  6. }
  7. }

编写spi

在这里插入图片描述

  1. 添加resources/META-INF/services/com.mine.DemoInterface
  2. 文件内容是impl的类名:com.mine.DemoInterfaceImpl

在main中实现调用

  1. public class Main {
  2. public static void main(String[] args) {
  3. ServiceLoader<DemoInterface> load = ServiceLoader.load(DemoInterface.class);
  4. for (DemoInterface demoInterface : load) {
  5. demoInterface.myTest();
  6. }
  7. }
  8. }

运行结果如下
在这里插入图片描述

评价

大多开源框都运用到了spi技术,例如mapStruct
在这里插入图片描述
重点的好处就是:解耦合,接口定义好了,可能有多重实现,通过spi来选,能让应用层无感知

发表评论

表情:
评论列表 (有 0 条评论,102人围观)

还没有评论,来说两句吧...

相关阅读