大家好,老 J。
前五期我们把 Spring Boot 的启动流程、自动配置、IoC 容器、Bean 实例化、循环依赖都讲完了。
这一期来讲一个贯穿整个 Spring Boot 的核心机制——SPI(Service Provider Interface)。
你可能没听说过这个名词,但你一定用过它的产物:spring.factories、自动配置、各种 Starter……底层都是 SPI。
一、什么是 SPI?
1. SPI 的概念
SPI 全称 Service Provider Interface,是 Java 提供的一种服务发现机制。
核心思想: 面向接口编程 + 运行时发现实现类。
传统方式:
// 代码中写死实现类Serviceservice=newUserServiceImpl();SPI 方式:
// 运行时动态发现实现类ServiceLoader<Service> loader = ServiceLoader.load(Service.class);for (Service service : loader) { service.execute();}2. SPI 的工作流程
1. 定义接口(在 API 模块) │ ▼2. 多个实现者实现接口(在各自的模块) │ ▼3. 在每个实现者的 META-INF/services/ 目录下, 创建以接口全限定名命名的文件, 文件内容是实现类的全限定名 │ ▼4. 调用方使用 ServiceLoader 加载3. 一个最简单的 SPI 示例
定义接口:
// com.example.api.MessageServicepublicinterfaceMessageService { String send(String message);}实现类1:
// com.example.impl.EmailServicepublicclassEmailServiceimplementsMessageService {@Overridepublic String send(String message) {return"Email: " + message; }}实现类2:
// com.example.impl.SmsServicepublicclassSmsServiceimplementsMessageService {@Overridepublic String send(String message) {return"SMS: " + message; }}SPI 配置文件:
# META-INF/services/com.example.api.MessageServicecom.example.impl.EmailServicecom.example.impl.SmsService使用 SPI:
publicclassMain {publicstaticvoidmain(String[] args) { ServiceLoader<MessageService> loader = ServiceLoader.load(MessageService.class);for (MessageService service : loader) { System.out.println(service.send("hello")); } }}// 输出:// Email: hello// SMS: hello二、Spring Boot 中的 SPI
Spring Boot 没有直接使用 Java 原生的 ServiceLoader,而是自己实现了一套更强大的 SPI 机制——SpringFactoriesLoader。
1. SpringFactoriesLoader 核心方法
// SpringFactoriesLoader.javapublicfinalclassSpringFactoriesLoader {// 加载指定类型的工厂实现类publicstatic <T> List<T> loadFactories(Class<T> factoryType, @Nullable ClassLoader classLoader) {// ... }// 加载指定类型的工厂实现类名称publicstatic List<String> loadFactoryNames(Class<?> factoryType, @Nullable ClassLoader classLoader) {// ... }}2. SpringFactoriesLoader 的工作原理
privatestatic Map<String, List<String>> loadSpringFactories(@Nullable ClassLoader classLoader) {// 1. 扫描所有 jar 包中的 META-INF/spring.factories 文件 Enumeration<URL> urls = classLoader.getResources("META-INF/spring.factories"); Map<String, List<String>> result = newHashMap<>();// 2. 遍历每个文件while (urls.hasMoreElements()) {URLurl= urls.nextElement();Propertiesproperties= PropertiesLoaderUtils.loadProperties(newUrlResource(url));// 3. 解析 key=value,key 是接口名,value 是实现类列表for (Map.Entry<?, ?> entry : properties.entrySet()) {StringfactoryTypeName= ((String) entry.getKey()).trim(); String[] factoryImplementationNames = StringUtils.commaDelimitedListToStringArray((String) entry.getValue());// 4. 合并到一个大 Map 中 result.computeIfAbsent(factoryTypeName, k -> newArrayList<>()) .addAll(Arrays.asList(factoryImplementationNames)); } }return result;}3. spring.factories 文件格式
# META-INF/spring.factories# 自动配置类org.springframework.boot.autoconfigure.EnableAutoConfiguration=\org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration,\org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration,\org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration# 应用程序监听器org.springframework.context.ApplicationListener=\org.springframework.boot.context.config.ConfigFileApplicationListener,\org.springframework.boot.env.EnvironmentPostProcessorApplicationListener# 初始化器org.springframework.context.ApplicationContextInitializer=\org.springframework.boot.context.ConfigurationWarningsApplicationContextInitializer三、SPI 在 Spring Boot 中的各种应用
1. 自动配置(最重要)
// AutoConfigurationImportSelector 中protected List<String> getCandidateConfigurations(...) {// 通过 SPI 加载所有自动配置类 List<String> configurations = SpringFactoriesLoader.loadFactoryNames( getSpringFactoriesLoaderFactoryClass(), // EnableAutoConfiguration.class getBeanClassLoader());return configurations;}2. 应用程序监听器
// SpringApplication 构造函数中publicSpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) {// ...// 从 spring.factories 加载 ApplicationListener setListeners((Collection) getSpringFactoriesInstances( ApplicationListener.class));}3. 应用程序初始化器
// SpringApplication 中publicSpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) {// ...// 从 spring.factories 加载 ApplicationContextInitializer setInitializers((Collection) getSpringFactoriesInstances( ApplicationContextInitializer.class));}4. 错误报告器
// SpringBootExceptionReporter 也是通过 SPI 加载的private SpringBootExceptionReporter getSpringBootExceptionReporter(...) {// 从 spring.factories 加载}5. 环境后置处理器
// EnvironmentPostProcessor 也是 SPISpringFactoriesLoader.loadFactories(EnvironmentPostProcessor.class, classLoader);四、Spring Boot 2.7+ 的变化
Spring Boot 2.7 开始逐步废弃 spring.factories,改用新的 AutoConfiguration.imports 文件。
旧方式(spring.factories):
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\com.example.hello.HelloAutoConfiguration新方式(AutoConfiguration.imports):
# META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.importscom.example.hello.HelloAutoConfiguration为什么要改?
• spring.factories被各种功能滥用,文件越来越大• 新格式更简洁,只服务于自动配置 • 为后续版本移除其他 SPI 做准备
五、自定义 SPI 扩展点
1. 定义接口
// 自定义的扩展点publicinterfaceCustomFormatter { String format(String input);}2. 实现接口
publicclassJsonFormatterimplementsCustomFormatter {@Overridepublic String format(String input) {return"{\"data\":\"" + input + "\"}"; }}publicclassXmlFormatterimplementsCustomFormatter {@Overridepublic String format(String input) {return"<data>" + input + "</data>"; }}3. 创建 SPI 配置文件
# META-INF/spring.factoriescom.example.spi.CustomFormatter=\com.example.spi.JsonFormatter,\com.example.spi.XmlFormatter4. 加载并使用
@ComponentpublicclassFormatService {private List<CustomFormatter> formatters;@PostConstructpublicvoidinit() {// 通过 SPI 加载所有实现 formatters = SpringFactoriesLoader.loadFactories( CustomFormatter.class, Thread.currentThread().getContextClassLoader() ); }public String format(String input) {// 使用第一个可用的格式化器if (!formatters.isEmpty()) {return formatters.get(0).format(input); }return input; }}六、SPI vs 其他扩展方式
| SPI | |||
| @Conditional | |||
| @Import | |||
| @ComponentScan |
七、面试高频问题
问题1:Spring Boot 的自动配置是如何加载的?
Spring Boot 通过 SPI 机制加载自动配置类。
1. @EnableAutoConfiguration注解导入AutoConfigurationImportSelector2. AutoConfigurationImportSelector调用SpringFactoriesLoader.loadFactoryNames()3. 加载所有 META-INF/spring.factories文件中 key 为EnableAutoConfiguration的配置类4. 然后通过 @Conditional条件注解过滤,得到最终生效的配置类
问题2:SpringFactoriesLoader 和 Java 原生 ServiceLoader 有什么区别?
@Order 和 Ordered | ||
问题3:如何自定义 Spring Boot 的 SPI 扩展点?
1. 定义接口 2. 在 META-INF/spring.factories中配置接口和实现类3. 通过 SpringFactoriesLoader.loadFactories()加载Spring Boot 内置了大量的 SPI 扩展点,如
ApplicationListener、ApplicationContextInitializer、EnvironmentPostProcessor等。
八、一张图总结
┌─────────────────────────────────────────────────────────────────────┐│ SpringFactoriesLoader ││ ││ 扫描所有 META-INF/spring.factories 文件 ││ │ ││ ▼ ││ ┌────────────────────────────────────────────────────────────┐ ││ │ spring.factories 内容示例 │ ││ │ │ ││ │ org.springframework.boot.autoconfigure.EnableAutoConf=\ │ ││ │ xxx.AutoConf1,\ │ ││ │ xxx.AutoConf2 │ ││ │ │ ││ │ org.springframework.context.ApplicationListener=\ │ ││ │ xxx.Listener1,\ │ ││ │ xxx.Listener2 │ ││ └────────────────────────────────────────────────────────────┘ ││ │ ││ ▼ ││ 按 key 获取实现类列表 ││ │ ││ ┌──────────┼──────────┬──────────────┐ ││ ▼ ▼ ▼ ▼ ││ EnableAuto Application Application Environment ││ Config Listener Initializer PostProcessor ││ │ │ │ │ ││ ▼ ▼ ▼ ▼ ││ 自动配置 事件监听 容器初始化 环境后处理 │└─────────────────────────────────────────────────────────────────────┘九、下期预告
Spring Boot 源码解析(七):Spring Boot 的启动流程复盘与面试指南
• 完整启动流程复盘(一图流) • 面试高频 20 问 • 源码学习建议 • 系列总结
十、互动时间
关于 SPI,你还有什么疑问?
• spring.factories和AutoConfiguration.imports的区别?• 如何调试 SPI 加载过程? • 自定义 Starter 的最佳实践?
评论区聊聊,老 J 给你解答。
我是老 J,下期见。
夜雨聆风