java spi实现案例
简介
SPI(Service Provider Interface),是JDK内置的一种 服务提供发现机制,可以用来扩展和替换组件,主要是被框架的开发人员使用。
核心代码
spi接口定义
public interface UserSpi { /** * 获取用户信息 * * @param id 用户ID * @return 用户信息 */ User getUserById(Long id); }
spi实现提供者1
<!-- 引入spi --> <dependencies> <dependency> <groupId>org.example</groupId> <artifactId>spi</artifactId> <version>1.0-SNAPSHOT</version> </dependency> </dependencies>
public class UserSpiImpl1 implements UserSpi { @Override public User getUserById(Long id) { return new User(1L, "张三"); } }
spi实现提供者2
<!-- 引入spi --> <dependencies> <dependency> <groupId>org.example</groupId> <artifactId>spi</artifactId> <version>1.0-SNAPSHOT</version> </dependency> </dependencies>
public class UserSpiImpl2 implements UserSpi { @Override public User getUserById(Long id) { return new User(2L, "李四"); } }
使用者测试
<!-- spi定义模块 --> <dependency> <groupId>org.example</groupId> <artifactId>spi</artifactId> <version>1.0-SNAPSHOT</version> </dependency> <!-- spi实现模块1 --> <dependency> <groupId>org.example</groupId> <artifactId>spi-impl1</artifactId> <version>1.0-SNAPSHOT</version> </dependency> <!-- spi实现模块2 --> <dependency> <groupId>org.example</groupId> <artifactId>spi-impl2</artifactId> <version>1.0-SNAPSHOT</version> </dependency>
public class Test { public static void main(String[] args) { ServiceLoader<UserSpi> s = ServiceLoader.load(UserSpi.class); Iterator<UserSpi> iterator = s.iterator(); while (iterator.hasNext()) { //如果存在多个实现类,则会遍历调用 UserSpi userSpi = iterator.next(); User user = userSpi.getUserById(1L); System.out.println(user); } } }
源码
github: https://github.com/hdwang123/spitest
参考文章
https://blog.csdn.net/weixin_45987961/article/details/121052452