我是靠谱客的博主 懵懂羊,这篇文章主要介绍SpringBoot神器SPI机制学习!!!前言例子例子2,现在分享给大家,希望可以做个参考。

SpringBoot学习之SPI机制浅析

  • 前言
  • 例子
  • 例子2
    • 现在假设有个需求我们要新增银联支付

前言

SpringBoot的零配置之一就是基于SPI。能很好的做扩展。
本篇学习下SpringBoot集成第三方技术的核心前置知识SPI的模式。


例子

ServiceLoader类是java.util下的
在这里插入图片描述
接口,解析文档的接口

复制代码
1
2
3
4
public interface IPraseDoc { void prase(); }

解析Excel的实现类

复制代码
1
2
3
4
5
6
7
public class ExcelParse implements IPraseDoc { @Override public void prase() { System.out.println("解析excel"); } }

假设我们现在要加个解析Word的实现类,那这里呢我们不用工厂方法模式。用SPI的方式去做。

加个解析Word实现类

复制代码
1
2
3
4
5
6
7
public class WordParse implements IPraseDoc { @Override public void prase() { System.out.println("解析word"); } }

配置我们的SPI
在这里插入图片描述
编写启动测试

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class MainStart { public static void main(String[] args) { ServiceLoader<IPraseDoc> serviceLoader= ServiceLoader.load(IPraseDoc.class); for (IPraseDoc iPraseDoc : serviceLoader) { iPraseDoc.prase(); //还可以去走某个接口 //if(iPraseDoc instanceof WordParse){ //iPraseDoc.prase(); //} } } }

运行结果:
在这里插入图片描述
这样的话我们新加的接口都可以在配置文件里装入。代码的耦合性大大降低。

原理:原理就是反射的方式。

在这里插入图片描述

例子2

利用SPI机制再来实现个类似支付平台的功能
在这里插入图片描述

在这里插入图片描述
公用的支付接口

复制代码
1
2
3
4
5
6
7
8
public interface PayStrategy { /** * 共同方法 * @return */ String toPayHtml(); }

支付宝支付的方式

复制代码
1
2
3
4
5
6
7
public class AliPayStrategy implements PayStrategy { @Override public String toPayHtml() { return "支付宝支付"; } }

微信支付的方式

复制代码
1
2
3
4
5
6
7
public class WeiXInPayStrategy implements PayStrategy { @Override public String toPayHtml() { return "微信支付"; } }

根据支付类型进行相应调用的类

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
public class PayContextStrategy { public static void getPayStrategy(Class<?> clazz) { ServiceLoader<PayStrategy> serviceLoader=ServiceLoader.load(PayStrategy.class); for (PayStrategy payStrategy : serviceLoader) { if(payStrategy.getClass()==clazz){ System.out.println(payStrategy.toPayHtml()); break; } } } }

进行微信支付的调用

复制代码
1
2
3
4
public static void main(String[] args) { getPayStrategy(WeiXInPayStrategy.class); }

在这里插入图片描述

现在假设有个需求我们要新增银联支付

在这里插入图片描述
在这里插入图片描述
只需要进行这两步,我们就完成了银联支付

上边的例子非常简单,实际业务中,我们还需要堆入参和出参,回调等进行相关的编写,但是骨架是这样的,我们进行不同的扩展添加即可。

最后

以上就是懵懂羊最近收集整理的关于SpringBoot神器SPI机制学习!!!前言例子例子2的全部内容,更多相关SpringBoot神器SPI机制学习内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(65)

评论列表共有 0 条评论

立即
投稿
返回
顶部