news 2026/4/15 12:06:03

Spring Boot 集成分析

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
Spring Boot 集成分析

1. 工程结构概览

Spring AI 通过 Spring Boot Starter 和 Auto Configuration 机制,实现了零配置的 AI 应用开发。开发者只需要添加依赖和配置属性,就能使用各种 AI 能力。

spring-ai-spring-boot-starters/ # Starter 模块

├── spring-ai-starter-model-openai/ # OpenAI Starter

├── spring-ai-starter-model-ollama/ # Ollama Starter

├── spring-ai-starter-vector-store-pgvector/ # PGVector Starter

└── ... (50+ 个 Starter)

auto-configurations/ # 自动配置模块

├── models/ # 模型自动配置

│ ├── spring-ai-autoconfigure-model-openai/

│ ├── spring-ai-autoconfigure-model-ollama/

│ └── ...

├── vector-stores/ # 向量存储自动配置

│ ├── spring-ai-autoconfigure-vector-store-pgvector/

│ └── ...

├── common/ # 通用自动配置

│ ├── spring-ai-autoconfigure-retry/

│ └── spring-ai-autoconfigure-model-tool/

└── mcp/ # MCP 自动配置

2. 技术体系与模块关系

Spring Boot 集成采用 Starter + Auto Configuration 模式:

image.png

3. 关键场景示例代码

3.1 最简单的使用

只需要添加依赖和配置:

<dependency>

<groupId>org.springframework.ai</groupId>

<artifactId>spring-ai-starter-model-openai</artifactId>

</dependency>

spring:

ai:

openai:

api-key: ${OPENAI_API_KEY}

chat:

options:

model: gpt-4

@RestController

public class ChatController {

@Autowired

private ChatModel chatModel; // 自动注入

@GetMapping("/chat")

public String chat(String message) {

return chatModel.call(message);

}

}

3.2 配置属性

所有配置都通过 application.yml 或 application.properties:

spring:

ai:

openai:

api-key: ${OPENAI_API_KEY}

base-url: https://api.openai.com

chat:

options:

model: gpt-4

temperature: 0.7

max-tokens: 1000

embedding:

options:

model: text-embedding-3-small

3.3 条件装配

自动配置会根据条件决定是否启用:

@AutoConfiguration

@ConditionalOnClass(OpenAiChatModel.class)

@ConditionalOnProperty(

prefix = "spring.ai.openai.chat",

name = "enabled",

havingValue = "true",

matchIfMissing = true

)

public class OpenAiChatAutoConfiguration {

// ...

}

3.4 自定义 Bean

可以覆盖自动配置的 Bean:

@Configuration

public class CustomConfig {

@Bean

@Primary

public ChatModel customChatModel() {

// 自定义实现

return new CustomChatModel();

}

}

4. 核心实现图

4.1 自动配置流程

image.png

5. 入口类与关键类关系

image.png

6. 关键实现逻辑分析

6.1 Starter 设计

Starter 是一个空的 Maven 模块,只包含依赖:

<dependencies>

<!-- 核心实现 -->

<dependency>

<groupId>org.springframework.ai</groupId>

<artifactId>spring-ai-openai</artifactId>

</dependency>

<!-- 自动配置 -->

<dependency>

<groupId>org.springframework.ai</groupId>

<artifactId>spring-ai-autoconfigure-model-openai</artifactId>

</dependency>

<!-- 通用自动配置 -->

<dependency>

<groupId>org.springframework.ai</groupId>

<artifactId>spring-ai-autoconfigure-retry</artifactId>

</dependency>

</dependencies>

Starter 的优势:

简化依赖管理:用户只需要添加一个依赖

版本统一:所有相关依赖版本统一管理

功能完整:包含所有必需的依赖

6.2 自动配置类实现

自动配置类使用条件注解:

@AutoConfiguration

@ConditionalOnClass(OpenAiChatModel.class)

@ConditionalOnProperty(

prefix = "spring.ai.openai.chat",

name = "enabled",

havingValue = "true",

matchIfMissing = true

)

@EnableConfigurationProperties(OpenAiChatProperties.class)

public class OpenAiChatAutoConfiguration {

@Bean

@ConditionalOnMissingBean

public OpenAiChatModel chatModel(

OpenAiChatProperties properties,

RetryTemplate retryTemplate,

RestClient.Builder restClientBuilder

) {

// 1. 构建 API 客户端

OpenAiApi openAiApi = new OpenAiApi(

properties.getBaseUrl(),

properties.getApiKey(),

restClientBuilder,

retryTemplate

);

// 2. 创建 ChatModel

return new OpenAiChatModel(

openAiApi,

properties.getChat().getOptions()

);

}

@Bean

@ConditionalOnMissingBean

public OpenAiChatOptions chatOptions(OpenAiChatProperties properties) {

return properties.getChat().getOptions();

}

}

关键注解说明:

@AutoConfiguration:标记为自动配置类

@ConditionalOnClass:只有当类路径存在指定类时才启用

@ConditionalOnProperty:只有当配置属性满足条件时才启用

@ConditionalOnMissingBean:只有当容器中不存在指定 Bean 时才创建

@EnableConfigurationProperties:启用配置属性绑定

6.3 配置属性绑定

配置属性类使用 @ConfigurationProperties:

@ConfigurationProperties(prefix = "spring.ai.openai")

public class OpenAiChatProperties {

private String apiKey;

private String baseUrl = "https://api.openai.com";

private Chat chat = new Chat();

public static class Chat {

private boolean enabled = true;

private OpenAiChatOptions options = new OpenAiChatOptions();

// getters and setters

}

// getters and setters

}

配置属性支持:

类型安全:强类型绑定

IDE 提示:通过 spring-boot-configuration-processor 生成元数据

验证:支持 JSR-303 验证注解

6.4 自动配置注册

自动配置类通过 META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports 注册:

org.springframework.ai.model.openai.autoconfigure.OpenAiChatAutoConfiguration

org.springframework.ai.model.openai.autoconfigure.OpenAiEmbeddingAutoConfiguration

org.springframework.ai.model.openai.autoconfigure.OpenAiImageAutoConfiguration

Spring Boot 3.x 使用 AutoConfiguration.imports 文件(替代了之前的 spring.factories)。

6.5 条件装配机制

Spring AI 使用多种条件注解:

// 1. 类路径条件

@ConditionalOnClass(OpenAiChatModel.class)

// 2. 配置属性条件

@ConditionalOnProperty(

prefix = "spring.ai.openai.chat",

name = "enabled",

havingValue = "true"

)

// 3. Bean 存在条件

@ConditionalOnMissingBean(ChatModel.class)

// 4. 资源条件

@ConditionalOnResource(resources = "classpath:openai-config.properties")

这些条件让自动配置变得智能:

按需加载:只加载需要的配置

避免冲突:不会覆盖用户自定义的 Bean

灵活配置:可以通过配置属性控制行为

6.6 重试机制自动配置

重试是 AI 应用的重要能力:

@AutoConfiguration

@ConditionalOnClass(RetryUtils.class)

@EnableConfigurationProperties(SpringAiRetryProperties.class)

public class SpringAiRetryAutoConfiguration {

@Bean

@ConditionalOnMissingBean

public RetryTemplate retryTemplate(SpringAiRetryProperties properties) {

return RetryTemplate.builder()

.maxAttempts(properties.getMaxAttempts())

.retryOn(TransientAiException.class)

.retryOn(ResourceAccessException.class)

.exponentialBackoff(

properties.getBackoff().getInitialInterval(),

properties.getBackoff().getMultiplier(),

properties.getBackoff().getMaxInterval()

)

.build();

}

}

配置示例:

spring:

ai:

retry:

max-attempts: 3

backoff:

initial-interval: 1s

multiplier: 2.0

max-interval: 10s

6.7 工具调用自动配置

工具调用自动配置:

@AutoConfiguration

@ConditionalOnClass({ToolCallingManager.class, ChatModel.class})

public class ToolCallingAutoConfiguration {

@Bean

@ConditionalOnMissingBean

public ToolCallingManager toolCallingManager(

ObservationRegistry observationRegistry,

ToolCallbackResolver toolCallbackResolver

) {

return new DefaultToolCallingManager(

observationRegistry,

toolCallbackResolver,

new DefaultToolExecutionExceptionProcessor()

);

}

@Bean

@ConditionalOnMissingBean

public ToolCallbackResolver toolCallbackResolver(ApplicationContext context) {

return new DelegatingToolCallbackResolver(

new SpringBeanToolCallbackResolver(context),

new StaticToolCallbackResolver()

);

}

}

7. 配置属性管理

7.1 配置属性层次

Spring AI 的配置属性采用层次结构:

spring:

ai:

openai: # 提供商级别

api-key: xxx

chat: # 功能级别

enabled: true

options: # 选项级别

model: gpt-4

temperature: 0.7

7.2 配置属性验证

支持 JSR-303 验证:

@ConfigurationProperties(prefix = "spring.ai.openai")

@Validated

public class OpenAiChatProperties {

@NotBlank

private String apiKey;

@Min(0)

@Max(2)

private Double temperature;

}

7.3 配置属性提示

通过 additional-spring-configuration-metadata.json 提供 IDE 提示:

{

"properties": [{

"name": "spring.ai.openai.chat.options.model",

"type": "java.lang.String",

"description": "The model to use for chat completions.",

"defaultValue": "gpt-3.5-turbo"

}]

}

8. Bean 创建流程

8.1 Bean 创建顺序

自动配置的 Bean 创建顺序:

配置属性 Bean:首先创建配置属性 Bean

依赖 Bean:创建依赖的 Bean(如 RetryTemplate)

核心 Bean:创建核心功能 Bean(如 ChatModel)

增强 Bean:创建增强功能 Bean(如 Advisor)

8.2 Bean 覆盖机制

用户可以通过 @Primary 或 @ConditionalOnMissingBean 覆盖自动配置的 Bean:

@Configuration

public class CustomConfig {

@Bean

@Primary // 优先使用

public ChatModel customChatModel() {

return new CustomChatModel();

}

}

9. 外部依赖

9.1 Spring Boot

spring-boot-starter:核心 Starter

spring-boot-autoconfigure:自动配置支持

spring-boot-configuration-processor:配置属性处理

9.2 Spring Framework

spring-context:IoC 容器

spring-beans:Bean 管理

spring-core:核心功能

10. 工程总结

Spring AI 的 Spring Boot 集成设计有几个亮点:

零配置理念。通过 Starter 和 Auto Configuration,用户只需要添加依赖和配置属性,就能使用 AI 能力,无需编写任何配置代码。想用 OpenAI?加个依赖,配个 API Key,就能用了。

条件装配。使用 @ConditionalOn* 注解,让自动配置变得智能,只加载需要的配置,避免不必要的 Bean 创建

配置属性驱动。所有配置都通过 application.yml 或 application.properties,支持类型安全和 IDE 提示。写配置时有自动补全,写错了编译期就能发现。

可扩展性。用户可以轻松覆盖自动配置的 Bean,实现自定义行为。想自定义 ChatModel?加个 @Primary 注解就行。

模块化设计。每个功能都有独立的 Starter 和 Auto Configuration,用户可以选择性地添加需要的功能。想用向量存储?加个 spring-ai-starter-vector-store-pgvector 就行。

总的来说,Spring AI 的 Spring Boot 集成既简单又强大。简单的使用方式降低了学习成本,强大的自动配置机制让系统可以适应各种场景。这种设计让开发者可以快速构建 AI 应用,同时也能根据需求进行深度定制。

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/4/14 7:19:50

电商数据分析实战:union all和union的典型应用场景

快速体验 打开 InsCode(快马)平台 https://www.inscode.net输入框内输入如下内容&#xff1a; 开发一个电商数据分析演示项目&#xff0c;展示union和union all的实际应用。包含&#xff1a;1. 模拟电商订单和用户数据 2. 展示合并销售报表的两种方式 3. 性能对比测试模块 4. …

作者头像 李华
网站建设 2026/4/7 18:55:00

如何用AI自动生成ST-Link调试工具代码

快速体验 打开 InsCode(快马)平台 https://www.inscode.net输入框内输入如下内容&#xff1a; 请生成一个完整的ST-Link调试工具项目&#xff0c;包含以下功能&#xff1a;1. ST-Link V2/V3固件通信协议实现 2. 支持STM32芯片的读写操作 3. 提供Flash编程接口 4. 包含调试控制…

作者头像 李华
网站建设 2026/4/12 23:52:04

视频质量优化实战:用ffmpeg-python打造智能诊断系统

视频质量优化实战&#xff1a;用ffmpeg-python打造智能诊断系统 【免费下载链接】ffmpeg-python Python bindings for FFmpeg - with complex filtering support 项目地址: https://gitcode.com/gh_mirrors/ff/ffmpeg-python 还在为视频处理中的画质波动而烦恼吗&#x…

作者头像 李华
网站建设 2026/4/6 12:41:50

CatBoost在电商推荐系统中的应用案例

快速体验 打开 InsCode(快马)平台 https://www.inscode.net输入框内输入如下内容&#xff1a; 构建一个电商推荐系统的原型&#xff0c;使用CatBoost模型预测用户购买概率。输入数据包括用户浏览历史、商品类别和用户 demographics。要求生成数据处理管道、模型训练代码和评估…

作者头像 李华
网站建设 2026/4/12 8:39:09

KolodaView开源贡献指南:从零开始参与iOS卡片组件开发

KolodaView开源贡献指南&#xff1a;从零开始参与iOS卡片组件开发 【免费下载链接】Koloda KolodaView is a class designed to simplify the implementation of Tinder like cards on iOS. 项目地址: https://gitcode.com/gh_mirrors/ko/Koloda KolodaView是一个专为i…

作者头像 李华
网站建设 2026/4/12 18:49:19

如何创建自己的数字人?2025最全解析与实践指南

在 2025 年的数字创作浪潮中&#xff0c;“拥有属于自己的数字人”正成为越来越多创作者与企业的共同目标。从短视频内容批量生成&#xff0c;到直播电商的全天候在线虚拟主播&#xff0c;再到文旅讲解、企业培训、政务服务等多场景的智能交互&#xff0c;数字人正在从“技术奇…

作者头像 李华