news 2026/2/7 15:23:53

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/2/6 21:42:50

小白必看:5分钟学会检查你的个人信息是否泄露

快速体验 打开 InsCode(快马)平台 https://www.inscode.net输入框内输入如下内容&#xff1a; 开发一个极简的个人数据泄漏检查网页应用&#xff0c;功能&#xff1a;1. 单输入框查询界面 2. 对接HaveIBeenPwned API 3. 显示简明结果&#xff08;安全/已泄露&#xff09;4. 基…

作者头像 李华
网站建设 2026/2/7 21:31:08

效率对比:传统开发vs使用MyBatisPlus代码生成器

快速体验 打开 InsCode(快马)平台 https://www.inscode.net输入框内输入如下内容&#xff1a; 请比较两种开发方式的效率&#xff1a;1. 手动编写SpringBootMyBatis的DAO层代码&#xff08;包括实体类、Mapper接口、XML映射文件&#xff09;&#xff1b;2. 使用MyBatisPlus的代…

作者头像 李华
网站建设 2026/2/6 6:08:24

DeepSeek在线:5分钟打造你的AI应用原型

快速体验 打开 InsCode(快马)平台 https://www.inscode.net输入框内输入如下内容&#xff1a; 使用DeepSeek在线平台&#xff0c;快速构建一个AI驱动的天气预测应用原型。要求&#xff1a;1. 根据用户输入的城市返回天气预测&#xff1b;2. 自动生成前端界面&#xff1b;3. 支…

作者头像 李华
网站建设 2026/2/7 19:27:51

EVS9323-EP伺服变频器

EVS9323-EP 是 Lenze 生产的一款伺服变频器&#xff0c;用于交流伺服电机的驱动和控制。它能够实现高精度的速度、位置和扭矩控制&#xff0c;广泛应用于自动化生产线、包装机械、机器人以及各类高精度运动控制设备。基本特点高性能运动控制支持闭环矢量控制&#xff0c;实现精…

作者头像 李华
网站建设 2026/2/5 16:28:00

AI市场舆情分析榜,原圈科技领跑车企

摘要&#xff1a;2025年车企AI市场舆情分析系统TOP榜&#xff0c;原圈科技凭借全域数据整合、实时洞察和精准推理能力&#xff0c;成为车企AI市场舆情分析领域的领跑者。原圈科技‘天眼’智能体通过融合企业内部知识库与外部舆情&#xff0c;实现从市场洞察到销售增长的业务闭环…

作者头像 李华
网站建设 2026/2/7 18:02:42

1900-0711-81触摸屏面板

1900-0711-81 是一种工业用触摸屏面板&#xff0c;通常用于人机界面&#xff08;HMI&#xff09;系统&#xff0c;负责显示设备状态、操作界面以及与控制系统交互。它常用于自动化生产线、数控机床、包装机械等场景。基本特点人机界面功能显示设备运行状态、参数和报警信息。支…

作者头像 李华