Spring AI 2.x 从入门到精通:软件架构师学习指南(2026 最新版)

适用对象:Java 开发者、系统架构师、AI 工程师
技术栈要求:熟悉 Spring Boot 3.x、Java 17+、基础 LLM 概念
Spring AI 版本:2.x(基于 main 分支,兼容 Spring Boot 4.x)
官方仓库:https://github.com/spring-projects/spring-ai
文档地址:https://docs.spring.io/spring-ai/reference/

一、Spring AI 2.x 是什么?有何重大变化?

Spring AI 2.x 是 Spring 官方推出的第二代 AI 应用开发框架,全面重构了 API 设计,引入了更现代、更灵活、更强大的抽象,以支持 生成式 AI 的复杂应用场景(如 Agent、RAG、Function Calling、Structured Output、Observability 等)。

✅ 核心升级亮点(vs 0.8.x):
特性 Spring AI 0.8.x Spring AI 2.x
核心 API AiClient ChatClient + EmbeddingClient(职责分离)

流式响应 CompletableFuture Reactor Flux 原生支持

结构化输出 手动 JSON Schema @JsonPropertyDescription + 自动 POJO 映射

工具调用 ToolCallback @Tool 注解 + 自动注册

对话记忆 手动维护上下文 内置 ChatMemory 抽象

可观测性 基础日志 Micrometer + OpenTelemetry 集成

向量存储 多个独立模块 统一 VectorStore API + SQL-like 元数据过滤

💡 设计哲学:

  • Fluent API:类似 WebClient/RestClient 的链式调用
  • POJO First:AI 输出直接映射到 Java 对象
  • 云原生友好:全面支持 Spring Boot 4 / Jakarta EE 10

二、整体功能与技术架构(2.x)

  1. 功能全景图

graph LR
A[用户] --> B[ChatClient]
B --> C{模型提供商}
C --> D[OpenAI]
C --> E[Anthropic]
C --> F[Ollama]
C --> G[Azure]
C --> H[Google Vertex AI]
B --> I[RAG Pipeline]
I --> J[Document Reader]
I --> K[Text Splitter]
I --> L[EmbeddingClient]
I --> M[VectorStore]
M --> N
M --> O
M --> P
M --> Q
B --> R[Function Calling]
R --> S[@Tool 注解方法]
B --> T[ChatMemory]
T --> U[In-Memory]
T --> V[Redis]
B --> W[Observability]
W --> X[Micrometer]
W --> Y[OpenTelemetry]

  1. 核心模块分层
    层级 模块 说明
    客户端层 spring-ai-core ChatClient, EmbeddingClient, Prompt

模型实现 spring-ai-openai 等 各厂商客户端(自动配置)

RAG 支持 spring-ai-document 文档加载与 ETL

spring-ai-embedding 嵌入模型抽象

spring-ai-vectorstore-* 向量存储(统一 API)

高级能力 spring-ai-function-calling @Tool 注解驱动

spring-ai-chat-memory 对话状态管理

spring-ai-observability 指标与追踪

启动器 *-spring-boot-starter 自动装配(start.spring.io 可选)

三、核心源码解析(Spring AI 2.x)

  1. 新一代核心:ChatClient(Fluent API)

取代旧版 AiClient,提供链式调用和响应式支持。

// org.springframework.ai.chat.client.ChatClient
public interface ChatClient {

// 同步调用
ChatResponse call(String prompt);

// 异步(Reactor)
Flux stream(String prompt);

// 构建器模式(推荐)
default PromptBuilder prompt() {
    return new PromptBuilder();
}

interface PromptBuilder {
    PromptBuilder system(String systemMessage);
    PromptBuilder user(String userMessage);
    PromptBuilder functions(List tools);
    PromptBuilder memory(ChatMemory chatMemory);
    ChatResponse call();
    Flux stream();
}

}

✅ 优势:

  • 链式构建 Prompt,代码可读性高
  • 原生支持 Flux 流式响应(适合长文本生成)
  1. 结构化输出:POJO 自动映射

通过 @JsonPropertyDescription 注解定义字段语义,AI 自动填充。

// 定义响应结构
public class WeatherInfo {

@JsonPropertyDescription("城市名称,例如:北京")
private String city;

@JsonPropertyDescription("当前温度,单位摄氏度")
private Integer temperature;

// getters/setters

}

调用方式:
ChatClient chatClient = // …

WeatherInfo weather = chatClient.prompt()
.user(“上海今天的天气怎么样?”)
.call()
.entity(WeatherInfo.class); // 自动映射!

🔍 底层原理:
框架自动将 POJO 转为 JSON Schema,并设置 response_format,模型返回 JSON 后反序列化。

  1. 函数调用:@Tool 注解

将任意 Spring Bean 方法暴露为 AI 可调用工具。

@Component
public class WeatherService {

@Tool("获取指定城市的当前天气")
public WeatherInfo getWeather(@ToolParam("城市名称") String city) {
    // 调用真实天气 API
    return new WeatherInfo(city, 25);
}

}

使用:
ChatResponse response = chatClient.prompt()
.user(“上海今天天气如何?”)
.functions(ToolUtils.findTools(weatherService)) // 自动注册
.call();

// 框架自动处理 ToolCall → 执行方法 → 返回结果
String answer = response.getResult().getOutput().getContent();

✅ 优势:

  • 无需手动解析 tool_calls
  • 类型安全,参数自动校验
  1. 对话记忆:ChatMemory

自动管理多轮对话上下文。

// 内存实现(测试用)
ChatMemory chatMemory = new InMemoryChatMemory();

// Redis 实现(生产用)
@Bean
public ChatMemory chatMemory(RedisConnectionFactory connectionFactory) {
return new RedisChatMemory(connectionFactory);
}

// 使用
ChatResponse response = chatClient.prompt()
.user(“我叫张三”)
.memory(chatMemory)
.call();

// 下一轮自动带上历史
ChatResponse next = chatClient.prompt()
.user(“我叫什么?”)
.memory(chatMemory)
.call(); // AI 回答:“张三”

  1. 向量存储:统一 API + 元数据过滤

所有向量库实现 VectorStore 接口,支持 SQL-like 过滤。

// 存储文档
vectorStore.add(List.of(
new Document(“Spring AI 很强大”, Map.of(“author”, “张三”, “year”, 2025)),
new Document(“Java 是最好的语言”, Map.of(“author”, “李四”, “year”, 2024))
));

// 检索:带元数据过滤
List results = vectorStore.similaritySearch(
SearchRequest.query(“AI 框架”)
.withTopK(2)
.withFilterExpression(“author == ‘张三’ && year >= 2025”) // 类 SQL 语法
);

🔧 支持的向量库:PGVector, Redis, Milvus, Weaviate, Pinecone, Qdrant 等 15+ 种。

四、典型使用场景与代码示例(2.x)

场景 1:基础聊天(带流式响应)

@RestController
public class ChatController {

private final ChatClient chatClient;

public ChatController(ChatClient.Builder builder) {
    this.chatClient = builder.build();
}

@GetMapping(value = "/chat/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux chatStream(@RequestParam String message) {
    return chatClient.prompt()
            .user(message)
            .stream()
            .map(response -> response.getResult().getOutput().getContent());
}

}

✅ 适用:实时聊天、长文本生成(如小说、报告)

场景 2:RAG(检索增强生成)

@Service
public class RagService {

private final ChatClient chatClient;
private final VectorStore vectorStore;

public String ask(String question) {
    // 1. 检索相关文档
    List docs = vectorStore.similaritySearch(SearchRequest.query(question).withTopK(3));

    // 2. 构造上下文
    String context = docs.stream()
            .map(Document::getContent)
            .collect(Collectors.joining("n"));

    // 3. 调用 AI
    return chatClient.prompt()
            .system("基于以下上下文回答问题:n" + context)
            .user(question)
            .call()
            .content();
}

}

💡 增强:可结合 ChatMemory 实现多轮 RAG 对话。

场景 3:智能 Agent(自动工具调用)

@Component
public class AgentService {

private final ChatClient chatClient;
private final WeatherService weatherService; // 带 @Tool 注解

public String run(String goal) {
    return chatClient.prompt()
            .user(goal)
            .functions(ToolUtils.findTools(weatherService))
            .call()
            .content();
}

}

// 调用
String result = agentService.run(“查询北京和上海的天气,并比较哪个更热”);
// AI 自动调用 getWeather(“北京”) 和 getWeather(“上海”),然后比较

✅ 适用:自动化任务、多步骤推理、Agent 应用

场景 4:多模型切换(运行时动态)

@Configuration
public class AiConfig {

@Bean
@Primary
public ChatClient openAiClient(ChatClient.Builder builder) {
    return builder
            .options(OpenAiChatOptions.builder().withModel("gpt-4o").build())
            .build();
}

@Bean
public ChatClient ollamaClient(ChatClient.Builder builder) {
    return builder
            .options(OllamaOptions.builder().withModel("llama3:8b").build())
            .build();
}

}

// 使用
@Service
public class HybridService {

@Autowired
@Qualifier("ollamaClient")
private ChatClient localModel;

@Autowired
@Qualifier("openAiClient")
private ChatClient cloudModel;

public String generate(String prompt) {
    // 敏感内容用本地模型
    if (prompt.contains("隐私")) {
        return localModel.prompt().user(prompt).call().content();
    }
    return cloudModel.prompt().user(prompt).call().content();
}

}

五、高级架构能力

  1. 可观测性(Observability)

自动集成 Micrometer,记录 token 用量、延迟等指标。

application.yml
management:
metrics:
enable:
spring.ai: true
endpoints:
web:
exposure:
include: metrics,prometheus

访问 /actuator/metrics 可查看:

  • ai.chat.duration
  • ai.chat.tokens.input
  • ai.chat.tokens.output

📊 支持 Prometheus + Grafana 监控。

  1. Advisor 模式(AOP for AI)

通过 Advisor 封装通用 AI 模式(如重试、缓存、敏感词过滤)。

@Bean
public Advisor aiRetryAdvisor() {
return new RetryAdvisor(3); // 自动重试 3 次
}

@Bean
public Advisor aiCacheAdvisor(CacheManager cacheManager) {
return new CacheAdvisor(cacheManager.getCache(“ai-responses”));
}

✅ 适用:非侵入式增强 AI 调用行为。

  1. ETL 文档处理管道

内置文档加载 → 清洗 → 分块 → 嵌入流水线。

@Bean
public DocumentReader documentReader() {
return new PdfDocumentReader(); // 或 UrlReader, TextReader
}

@Bean
public TextSplitter textSplitter() {
return new TokenTextSplitter(500, 50); // 500 tokens, 50 overlap
}

// 自动构建 RAG 管道
@Bean
public Runnable ragPipeline(DocumentReader reader, TextSplitter splitter, VectorStore store) {
return () -> {
List docs = reader.get(“https://example.com/doc.pdf”);
List chunks = splitter.apply(docs);
store.add(chunks);
};
}

六、学习路径建议(2.x)
阶段 目标 行动
入门 跑通第一个 ChatClient 1. Spring Boot 4 项目2. 添加 spring-ai-openai-spring-boot-starter3. 调用 chatClient.prompt().user(“…”).call()

进阶 实现 RAG + 结构化输出 1. 集成 PGVector2. 定义 POJO + @JsonPropertyDescription3. 实现问答接口

精通 构建 Agent 应用 1. 编写 @Tool 方法2. 结合 ChatMemory3. 添加可观测性

架构 生产级部署 1. 多模型路由2. 缓存 + 限流3. 向量库高可用

七、总结

Spring AI 2.x 不再只是一个“AI 客户端封装”,而是一个完整的生成式 AI 应用开发平台。作为架构师,你应重点关注:

  1. ChatClient Fluent API —— 现代化调用方式
  2. POJO 结构化输出 —— 类型安全,告别 JSON 解析
  3. @Tool 注解驱动 —— 构建智能 Agent 的基石
  4. 统一向量存储 API —— 无缝切换向量数据库
  5. 云原生可观测性 —— 生产环境必备

🚀 立即行动:

  1. 访问 start.spring.io,选择 Spring AI Starter
  2. 克隆 spring-ai-examples
  3. 运行 chat-client 和 function-calling 示例

拥抱 Spring AI 2.x,构建下一代 Java 智能应用!Spring AI 2.x 从入门到精通:软件架构师学习指南(2026 最新版)

适用对象:Java 开发者、系统架构师、AI 工程师
技术栈要求:熟悉 Spring Boot 3.x、Java 17+、基础 LLM 概念
Spring AI 版本:2.x(基于 main 分支,兼容 Spring Boot 4.x)
官方仓库:https://github.com/spring-projects/spring-ai
文档地址:https://docs.spring.io/spring-ai/reference/

一、Spring AI 2.x 是什么?有何重大变化?

Spring AI 2.x 是 Spring 官方推出的第二代 AI 应用开发框架,全面重构了 API 设计,引入了更现代、更灵活、更强大的抽象,以支持 生成式 AI 的复杂应用场景(如 Agent、RAG、Function Calling、Structured Output、Observability 等)。

✅ 核心升级亮点(vs 0.8.x):
特性 Spring AI 0.8.x Spring AI 2.x
核心 API AiClient ChatClient + EmbeddingClient(职责分离)

流式响应 CompletableFuture Reactor Flux 原生支持

结构化输出 手动 JSON Schema @JsonPropertyDescription + 自动 POJO 映射

工具调用 ToolCallback @Tool 注解 + 自动注册

对话记忆 手动维护上下文 内置 ChatMemory 抽象

可观测性 基础日志 Micrometer + OpenTelemetry 集成

向量存储 多个独立模块 统一 VectorStore API + SQL-like 元数据过滤

💡 设计哲学:

  • Fluent API:类似 WebClient/RestClient 的链式调用
  • POJO First:AI 输出直接映射到 Java 对象
  • 云原生友好:全面支持 Spring Boot 4 / Jakarta EE 10

二、整体功能与技术架构(2.x)

  1. 功能全景图

graph LR
A[用户] --> B[ChatClient]
B --> C{模型提供商}
C --> D[OpenAI]
C --> E[Anthropic]
C --> F[Ollama]
C --> G[Azure]
C --> H[Google Vertex AI]
B --> I[RAG Pipeline]
I --> J[Document Reader]
I --> K[Text Splitter]
I --> L[EmbeddingClient]
I --> M[VectorStore]
M --> N
M --> O
M --> P
M --> Q
B --> R[Function Calling]
R --> S[@Tool 注解方法]
B --> T[ChatMemory]
T --> U[In-Memory]
T --> V[Redis]
B --> W[Observability]
W --> X[Micrometer]
W --> Y[OpenTelemetry]

  1. 核心模块分层
    层级 模块 说明
    客户端层 spring-ai-core ChatClient, EmbeddingClient, Prompt

模型实现 spring-ai-openai 等 各厂商客户端(自动配置)

RAG 支持 spring-ai-document 文档加载与 ETL

spring-ai-embedding 嵌入模型抽象

spring-ai-vectorstore-* 向量存储(统一 API)

高级能力 spring-ai-function-calling @Tool 注解驱动

spring-ai-chat-memory 对话状态管理

spring-ai-observability 指标与追踪

启动器 *-spring-boot-starter 自动装配(start.spring.io 可选)

三、核心源码解析(Spring AI 2.x)

  1. 新一代核心:ChatClient(Fluent API)

取代旧版 AiClient,提供链式调用和响应式支持。

// org.springframework.ai.chat.client.ChatClient
public interface ChatClient {

// 同步调用
ChatResponse call(String prompt);

// 异步(Reactor)
Flux stream(String prompt);

// 构建器模式(推荐)
default PromptBuilder prompt() {
    return new PromptBuilder();
}

interface PromptBuilder {
    PromptBuilder system(String systemMessage);
    PromptBuilder user(String userMessage);
    PromptBuilder functions(List tools);
    PromptBuilder memory(ChatMemory chatMemory);
    ChatResponse call();
    Flux stream();
}

}

✅ 优势:

  • 链式构建 Prompt,代码可读性高
  • 原生支持 Flux 流式响应(适合长文本生成)
  1. 结构化输出:POJO 自动映射

通过 @JsonPropertyDescription 注解定义字段语义,AI 自动填充。

// 定义响应结构
public class WeatherInfo {

@JsonPropertyDescription("城市名称,例如:北京")
private String city;

@JsonPropertyDescription("当前温度,单位摄氏度")
private Integer temperature;

// getters/setters

}

调用方式:
ChatClient chatClient = // …

WeatherInfo weather = chatClient.prompt()
.user(“上海今天的天气怎么样?”)
.call()
.entity(WeatherInfo.class); // 自动映射!

🔍 底层原理:
框架自动将 POJO 转为 JSON Schema,并设置 response_format,模型返回 JSON 后反序列化。

  1. 函数调用:@Tool 注解

将任意 Spring Bean 方法暴露为 AI 可调用工具。

@Component
public class WeatherService {

@Tool("获取指定城市的当前天气")
public WeatherInfo getWeather(@ToolParam("城市名称") String city) {
    // 调用真实天气 API
    return new WeatherInfo(city, 25);
}

}

使用:
ChatResponse response = chatClient.prompt()
.user(“上海今天天气如何?”)
.functions(ToolUtils.findTools(weatherService)) // 自动注册
.call();

// 框架自动处理 ToolCall → 执行方法 → 返回结果
String answer = response.getResult().getOutput().getContent();

✅ 优势:

  • 无需手动解析 tool_calls
  • 类型安全,参数自动校验
  1. 对话记忆:ChatMemory

自动管理多轮对话上下文。

// 内存实现(测试用)
ChatMemory chatMemory = new InMemoryChatMemory();

// Redis 实现(生产用)
@Bean
public ChatMemory chatMemory(RedisConnectionFactory connectionFactory) {
return new RedisChatMemory(connectionFactory);
}

// 使用
ChatResponse response = chatClient.prompt()
.user(“我叫张三”)
.memory(chatMemory)
.call();

// 下一轮自动带上历史
ChatResponse next = chatClient.prompt()
.user(“我叫什么?”)
.memory(chatMemory)
.call(); // AI 回答:“张三”

  1. 向量存储:统一 API + 元数据过滤

所有向量库实现 VectorStore 接口,支持 SQL-like 过滤。

// 存储文档
vectorStore.add(List.of(
new Document(“Spring AI 很强大”, Map.of(“author”, “张三”, “year”, 2025)),
new Document(“Java 是最好的语言”, Map.of(“author”, “李四”, “year”, 2024))
));

// 检索:带元数据过滤
List results = vectorStore.similaritySearch(
SearchRequest.query(“AI 框架”)
.withTopK(2)
.withFilterExpression(“author == ‘张三’ && year >= 2025”) // 类 SQL 语法
);

🔧 支持的向量库:PGVector, Redis, Milvus, Weaviate, Pinecone, Qdrant 等 15+ 种。

四、典型使用场景与代码示例(2.x)

场景 1:基础聊天(带流式响应)

@RestController
public class ChatController {

private final ChatClient chatClient;

public ChatController(ChatClient.Builder builder) {
    this.chatClient = builder.build();
}

@GetMapping(value = "/chat/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux chatStream(@RequestParam String message) {
    return chatClient.prompt()
            .user(message)
            .stream()
            .map(response -> response.getResult().getOutput().getContent());
}

}

✅ 适用:实时聊天、长文本生成(如小说、报告)

场景 2:RAG(检索增强生成)

@Service
public class RagService {

private final ChatClient chatClient;
private final VectorStore vectorStore;

public String ask(String question) {
    // 1. 检索相关文档
    List docs = vectorStore.similaritySearch(SearchRequest.query(question).withTopK(3));

    // 2. 构造上下文
    String context = docs.stream()
            .map(Document::getContent)
            .collect(Collectors.joining("n"));

    // 3. 调用 AI
    return chatClient.prompt()
            .system("基于以下上下文回答问题:n" + context)
            .user(question)
            .call()
            .content();
}

}

💡 增强:可结合 ChatMemory 实现多轮 RAG 对话。

场景 3:智能 Agent(自动工具调用)

@Component
public class AgentService {

private final ChatClient chatClient;
private final WeatherService weatherService; // 带 @Tool 注解

public String run(String goal) {
    return chatClient.prompt()
            .user(goal)
            .functions(ToolUtils.findTools(weatherService))
            .call()
            .content();
}

}

// 调用
String result = agentService.run(“查询北京和上海的天气,并比较哪个更热”);
// AI 自动调用 getWeather(“北京”) 和 getWeather(“上海”),然后比较

✅ 适用:自动化任务、多步骤推理、Agent 应用

场景 4:多模型切换(运行时动态)

@Configuration
public class AiConfig {

@Bean
@Primary
public ChatClient openAiClient(ChatClient.Builder builder) {
    return builder
            .options(OpenAiChatOptions.builder().withModel("gpt-4o").build())
            .build();
}

@Bean
public ChatClient ollamaClient(ChatClient.Builder builder) {
    return builder
            .options(OllamaOptions.builder().withModel("llama3:8b").build())
            .build();
}

}

// 使用
@Service
public class HybridService {

@Autowired
@Qualifier("ollamaClient")
private ChatClient localModel;

@Autowired
@Qualifier("openAiClient")
private ChatClient cloudModel;

public String generate(String prompt) {
    // 敏感内容用本地模型
    if (prompt.contains("隐私")) {
        return localModel.prompt().user(prompt).call().content();
    }
    return cloudModel.prompt().user(prompt).call().content();
}

}

五、高级架构能力

  1. 可观测性(Observability)

自动集成 Micrometer,记录 token 用量、延迟等指标。

application.yml
management:
metrics:
enable:
spring.ai: true
endpoints:
web:
exposure:
include: metrics,prometheus

访问 /actuator/metrics 可查看:

  • ai.chat.duration
  • ai.chat.tokens.input
  • ai.chat.tokens.output

📊 支持 Prometheus + Grafana 监控。

  1. Advisor 模式(AOP for AI)

通过 Advisor 封装通用 AI 模式(如重试、缓存、敏感词过滤)。

@Bean
public Advisor aiRetryAdvisor() {
return new RetryAdvisor(3); // 自动重试 3 次
}

@Bean
public Advisor aiCacheAdvisor(CacheManager cacheManager) {
return new CacheAdvisor(cacheManager.getCache(“ai-responses”));
}

✅ 适用:非侵入式增强 AI 调用行为。

  1. ETL 文档处理管道

内置文档加载 → 清洗 → 分块 → 嵌入流水线。

@Bean
public DocumentReader documentReader() {
return new PdfDocumentReader(); // 或 UrlReader, TextReader
}

@Bean
public TextSplitter textSplitter() {
return new TokenTextSplitter(500, 50); // 500 tokens, 50 overlap
}

// 自动构建 RAG 管道
@Bean
public Runnable ragPipeline(DocumentReader reader, TextSplitter splitter, VectorStore store) {
return () -> {
List docs = reader.get(“https://example.com/doc.pdf”);
List chunks = splitter.apply(docs);
store.add(chunks);
};
}

六、学习路径建议(2.x)
阶段 目标 行动
入门 跑通第一个 ChatClient 1. Spring Boot 4 项目2. 添加 spring-ai-openai-spring-boot-starter3. 调用 chatClient.prompt().user(“…”).call()

进阶 实现 RAG + 结构化输出 1. 集成 PGVector2. 定义 POJO + @JsonPropertyDescription3. 实现问答接口

精通 构建 Agent 应用 1. 编写 @Tool 方法2. 结合 ChatMemory3. 添加可观测性

架构 生产级部署 1. 多模型路由2. 缓存 + 限流3. 向量库高可用

七、总结

Spring AI 2.x 不再只是一个“AI 客户端封装”,而是一个完整的生成式 AI 应用开发平台。作为架构师,你应重点关注:

  1. ChatClient Fluent API —— 现代化调用方式
  2. POJO 结构化输出 —— 类型安全,告别 JSON 解析
  3. @Tool 注解驱动 —— 构建智能 Agent 的基石
  4. 统一向量存储 API —— 无缝切换向量数据库
  5. 云原生可观测性 —— 生产环境必备

🚀 立即行动:

  1. 访问 start.spring.io,选择 Spring AI Starter
  2. 克隆 spring-ai-examples
  3. 运行 chat-client 和 function-calling 示例

拥抱 Spring AI 2.x,构建下一代 Java 智能应用!

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐