Appearance
- 官网: https://spring.io/projects/spring-ai
- 官方文档(最新稳定版 1.0.2): https://docs.spring.io/spring-ai/reference/
- 中文教程(1.1.0): https://www.spring-doc.cn/spring-ai/1.1.0/index.html
- GitHub: https://github.com/spring-projects/spring-ai
- 最新版本: 1.1.4(2026年3月),预览版 2.0.0-M2
- 学习使用版本: 1.1.0
- 开源方: Spring(Broadcom)
- 开源协议: Apache 2.0
- 技术栈要求: Spring Boot 3.2+ / Java 17+
知识点清单
- [ ] Spring AI 是什么?定位与核心模块
- [ ] ChatClient Fluent API(同步 / 流式调用)
- [ ] Advisors 切面机制(AOP 风格的拦截器链)
- [ ] Chat Memory(对话记忆)管理
- [ ] Tool Calling(工具调用 / Function Calling)
- [ ] 工具调用 vs MCP 的区别
- [ ] RAG(检索增强生成)完整流程
- [ ] Structured Output(结构化输出 → POJO)
- [ ] MCP(模型上下文协议)的基本概念
- [ ] 多模态支持(Image / Audio / Moderation)
- [ ] 可观测性与生产特性(Micrometer / Retry / Testcontainers)
- [ ] 支持的模型提供商与向量数据库
笔记
一、Spring AI 是什么?
Spring AI 是 Spring 官方主导的开源项目,为 Java / Spring 生态提供统一、模块化、企业级的 AI 应用开发框架。核心理念:用 Spring 惯用的编程范式(POJO、自动配置、可观测、可测试)来集成现代 AI 能力。
总体来说,现在大模型的使用还在探索阶段,甚至有些 LLM 框架提出的概念是:使用越少的工具,让大模型本身去工作(因为有可能随着大模型的发展,有些工具的使用反而是限制了它的发挥)。因此还是看实际的使用效果和具体的提效去看大模型框架和大模型本身的发展。
核心模块:
| 模块 | 说明 |
|---|---|
| ChatClient | 对话生成(同步 + 流式),Fluent API |
| EmbeddingClient | 文本向量化 |
| ImageClient / AudioClient / ModerationClient | 多模态能力 |
| VectorStore | 统一向量数据库抽象 |
| RAG(RetrievalAugmenter) | 检索增强生成,内置文档 ETL 管道 |
| Advisors | 切面拦截器链,AOP 风格增强 LLM 调用 |
| Structured Output | LLM 输出直接映射为 POJO |
| Tool Calling | @Tool 注解注册工具,支持 MCP |
二、快速开始
xml
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-openai-spring-boot-starter</artifactId>
<version>1.0.2</version>
</dependency>yaml
spring:
ai:
openai:
api-key: ${OPENAI_API_KEY}
chat:
options:
model: gpt-4o
temperature: 0.7java
@RestController
public class AiController {
private final ChatClient chatClient;
public AiController(ChatClient.Builder builder) {
this.chatClient = builder.build();
}
@GetMapping("/ask")
public String ask(@RequestParam String q) {
return chatClient.prompt().user(q).call().content();
}
}三、ChatClient — Fluent API
ChatClient 是 Spring AI 的核心 API,取代了早期的 AiClient,采用 Fluent Builder 风格:
java
// 基础调用
String answer = chatClient.prompt()
.user("讲一个关于 Java 的笑话")
.call()
.content();
// 带系统提示词
String answer = chatClient.prompt()
.system("你是一个精通 Spring 的 Java 专家")
.user("解释一下 @Autowired 的原理")
.call()
.content();
// 流式输出
Flux<String> stream = chatClient.prompt()
.user("写一首诗")
.stream()
.content();四、Advisors — AOP 风格的拦截器链
Advisors 是 Spring AI 最具特色的设计,借鉴 Spring AOP 的理念,在 LLM 调用前后插入横切逻辑:
| AOP 概念 | Spring AI 对应 |
|---|---|
| Join Point | LLM 调用(chatClient.call()) |
| Advice | Advisor 执行的逻辑 |
| Pointcut | Advisor 的适用范围 |
内置 Advisor:
| Advisor | 作用 |
|---|---|
| SystemPromptAdvisor | 注入系统提示词 |
| MemoryAdvisor | 注入对话历史 |
| VectorStoreAdvisor | 从向量库检索上下文注入 |
| SimpleLoggerAdvisor | 记录请求/响应日志 |
| SafeGuardAdvisor | 拦截敏感/违规内容 |
| StructuredOutputAdvisor | 校验 JSON 输出格式 |
| ToolAroundAdvisor | 自定义工具调用循环 |
组合多个 Advisor:
java
ChatClient chatClient = ChatClient.builder(model)
.defaultAdvisors(
new SystemPromptAdvisor("你是一个有帮助的助手"),
new SimpleLoggerAdvisor(),
new SafeGuardAdvisor()
)
.build();五、聊天记忆(Chat Memory)
对话记忆让 LLM 在多轮对话中保持上下文:https://www.spring-doc.cn/spring-ai/1.1.0/api_chat-memory.html
Spring AI 支持多种记忆策略:
- InMemoryChatMemory:内存存储,适合开发
- CassandraChatMemory:分布式持久化
- JDBC / Redis ChatMemory:生产环境持久化
通过 MemoryAdvisor 自动注入历史对话,无需手动拼接。
六、工具调用(Tool / Function Calling)
让 LLM 能够调用外部工具(API、数据库、本地方法等),聊天对话文档:https://www.spring-doc.cn/spring-ai/1.1.0/api_chatmodel.html 。
java
public class OrderTools {
@Tool(name = "查询订单", description = "根据订单号查询订单状态")
public String getOrderStatus(@ToolParam(description = "订单号") String orderId) {
return "订单 " + orderId + " 状态:已发货";
}
}
// 注册工具并使用
ChatClient chatClient = ChatClient.builder(model)
.defaultTools(new OrderTools())
.build();LLM 会自动判断何时需要调用工具,Spring AI 负责工具调度和结果返回。
> 工具调用 和 MCP 的区别?
工具调用是"目的"(让 LLM 使用外部能力),而 MCP 是实现这一目的的"手段之一"(标准化的协议层)。MCP 将工具调用的"实现"和"使用"解耦,使得工具提供者可以跨语言、跨服务暴露能力。
> "工具"具体指什么?
工具是指 LLM 可调用的本地方法、脚本或函数。当 LLM 需要获取实时数据或执行特定操作时,通过 Function Calling 机制调用这些工具。
七、RAG(检索增强生成)
RAG 让 LLM 在回答问题前先从知识库检索相关内容,提高回答准确性和时效性:https://www.spring-doc.cn/spring-ai/1.1.0/api_retrieval-augmented-generation.html
完整流程:
文档加载 → 文档切分 → 向量化 → 存入 VectorStore
↓
用户提问 → 向量检索 → 上下文注入 Prompt → LLM 生成回答Spring AI 提供 DocumentReader / DocumentSplitter / VectorStore / RetrievalAugmenter 四大组件,覆盖 RAG 全链路:
java
// 构建 RAG Advisor
Advisor ragAdvisor = RetrievalAugmentationAdvisor.builder()
.documentRetriever(vectorStoreRetriever)
.build();
ChatClient chatClient = ChatClient.builder(model)
.defaultAdvisors(ragAdvisor)
.build();八、Structured Output(结构化输出)
LLM 返回的自然语言可以直接映射为 Java POJO,无需手动解析 JSON:
java
// 定义目标类型
public record Weather(String location, int temperature, String condition) {}
// 直接获取结构化结果
Weather weather = chatClient.prompt()
.user("查询今天北京的天气")
.call()
.entity(Weather.class);
System.out.println(weather.temperature()); // 直接使用通过 StructuredOutputAdvisor 可自动校验输出格式,确保 LLM 返回合法的结构化数据。
九、MCP(模型上下文协议)
MCP 是一种标准化协议,以结构化方式使 AI 模型与外部工具和资源交互:https://www.spring-doc.cn/spring-ai/1.1.0/api_mcp_mcp-overview.html
- MCP 将工具的"实现端"和"使用端"解耦
- 工具提供者通过 MCP Server 暴露能力,工具使用者通过 MCP Client 调用
- Spring AI 对 MCP 提供了一等公民支持
深入分析参见 MCP Java SDK的实现分析
十、多模态支持
Spring AI 1.0.x 提供专项 Client 处理多模态内容:
| Client | 能力 |
|---|---|
| ImageClient | 文本 → 图像生成 |
| AudioClient | TTS 语音合成 / ASR 语音识别 |
| ModerationClient | 内容安全审核 |
多模态数据(图片、音频)也可作为 Prompt 的一部分发送给支持视觉/音频输入的模型。
十一、可观测性与生产特性
Spring AI 深度集成 Spring 生态的生产级能力:
- Micrometer:自动上报 token 用量、延迟、错误率
- SLF4J:记录完整请求/响应(可脱敏)
- Spring Retry:请求失败自动重试
- Spring Security:API Key 管理和访问控制
- Testcontainers:基于真实向量数据库的集成测试
十二、支持的模型与向量数据库
模型提供商(20+): OpenAI、Anthropic Claude、Google Gemini/Vertex AI、Azure OpenAI、Amazon Bedrock、Ollama、DeepSeek、Moonshot(Kimi)、百度文心、智谱 GLM 等。所有提供商均支持同步 + 流式调用。
向量数据库(15+): PGVector、Chroma、Qdrant、Weaviate、Pinecone、Milvus、Redis、Elasticsearch、MongoDB Atlas、Neo4j、Oracle 等。
其他资源
- 新 MCP 注解开发 MCP Server:https://articles.zsxq.com/id_8wqg7j81poq6.html
- 框架 Spring AI Alibaba — 阿里基于 Spring AI 的增强框架(多智能体编排、Graph 工作流)
- 框架 AI框架选型对比 — 各框架差异与选型指南