Spring AI 从入门到精通

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. 功能全景图

渲染错误: Mermaid 渲染失败: Parse error on line 19: ...tion Calling]R --> S[@Tool 注解方法]B --> ----------------------^ Expecting 'AMP', 'COLON', 'PIPE', 'TESTSTR', 'DOWN', 'DEFAULT', 'NUM', 'COMMA', 'NODE_STRING', 'BRKT', 'MINUS', 'MULT', 'UNICODE_TEXT', got 'LINK_ID'

2. 核心模块分层

层级 模块 说明
客户端层 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,提供链式调用和响应式支持。

java 复制代码
// org.springframework.ai.chat.client.ChatClient
public interface ChatClient {

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

    // 异步(Reactor)
    Flux<ChatResponse> stream(String prompt);

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

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

优势

  • 链式构建 Prompt,代码可读性高
  • 原生支持 Flux 流式响应(适合长文本生成)

2. 结构化输出:POJO 自动映射

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

java 复制代码
// 定义响应结构
public class WeatherInfo {

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

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

    // getters/setters
}
调用方式:
java 复制代码
ChatClient chatClient = // ...

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

🔍 底层原理

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


3. 函数调用:@Tool 注解

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

java 复制代码
@Component
public class WeatherService {

    @Tool("获取指定城市的当前天气")
    public WeatherInfo getWeather(@ToolParam("城市名称") String city) {
        // 调用真实天气 API
        return new WeatherInfo(city, 25);
    }
}
使用:
java 复制代码
ChatResponse response = chatClient.prompt()
    .user("上海今天天气如何?")
    .functions(ToolUtils.findTools(weatherService)) // 自动注册
    .call();

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

优势

  • 无需手动解析 tool_calls
  • 类型安全,参数自动校验

4. 对话记忆:ChatMemory

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

java 复制代码
// 内存实现(测试用)
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 回答:"张三"

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

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

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

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

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


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

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

java 复制代码
@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<String> chatStream(@RequestParam String message) {
        return chatClient.prompt()
                .user(message)
                .stream()
                .map(response -> response.getResult().getOutput().getContent());
    }
}

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


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

java 复制代码
@Service
public class RagService {

    private final ChatClient chatClient;
    private final VectorStore vectorStore;

    public String ask(String question) {
        // 1. 检索相关文档
        List<Document> 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(自动工具调用)

java 复制代码
@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:多模型切换(运行时动态)

java 复制代码
@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 用量、延迟等指标。

yaml 复制代码
# 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 监控。


2. Advisor 模式(AOP for AI)

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

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

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

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


3. ETL 文档处理管道

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

java 复制代码
@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<Document> docs = reader.get("https://example.com/doc.pdf");
        List<Document> 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-clientfunction-calling 示例

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

Spring AI 的"记忆"分两层实现:短期记忆(上下文窗口) + 长期记忆(持久化到库)

下面结合最新源码与社区实践,用中文一次性讲透实现原理、代码入口与可直接落地的配置示例。


相关推荐
九.九11 小时前
ops-transformer:AI 处理器上的高性能 Transformer 算子库
人工智能·深度学习·transformer
春日见11 小时前
拉取与合并:如何让个人分支既包含你昨天的修改,也包含 develop 最新更新
大数据·人工智能·深度学习·elasticsearch·搜索引擎
恋猫de小郭11 小时前
AI 在提高你工作效率的同时,也一直在增加你的疲惫和焦虑
前端·人工智能·ai编程
deephub11 小时前
Agent Lightning:微软开源的框架无关 Agent 训练方案,LangChain/AutoGen 都能用
人工智能·microsoft·langchain·大语言模型·agent·强化学习
大模型RAG和Agent技术实践11 小时前
从零构建本地AI合同审查系统:架构设计与流式交互实战(完整源代码)
人工智能·交互·智能合同审核
老邋遢11 小时前
第三章-AI知识扫盲看这一篇就够了
人工智能
互联网江湖11 小时前
Seedance2.0炸场:长短视频们“修坝”十年,不如AI放水一天?
人工智能
青云计划12 小时前
知光项目知文发布模块
java·后端·spring·mybatis
PythonPioneer12 小时前
在AI技术迅猛发展的今天,传统职业该如何“踏浪前行”?
人工智能
赶路人儿12 小时前
Jsoniter(java版本)使用介绍
java·开发语言