惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
T
Troy Hunt's Blog
Scott Helme
Scott Helme
T
Threat Research - Cisco Blogs
T
Tenable Blog
L
LINUX DO - 热门话题
V
Visual Studio Blog
I
Intezer
Blog — PlanetScale
Blog — PlanetScale
Cisco Talos Blog
Cisco Talos Blog
A
Arctic Wolf
C
Cyber Attacks, Cyber Crime and Cyber Security
F
Fortinet All Blogs
aimingoo的专栏
aimingoo的专栏
Know Your Adversary
Know Your Adversary
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
N
Netflix TechBlog - Medium
SecWiki News
SecWiki News
I
InfoQ
Microsoft Security Blog
Microsoft Security Blog
Project Zero
Project Zero
W
WeLiveSecurity
Microsoft Azure Blog
Microsoft Azure Blog
A
About on SuperTechFans
Recorded Future
Recorded Future
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Vercel News
Vercel News
S
Securelist
Spread Privacy
Spread Privacy
L
LangChain Blog
云风的 BLOG
云风的 BLOG
G
Google Developers Blog
MongoDB | Blog
MongoDB | Blog
Google DeepMind News
Google DeepMind News
Recent Commits to openclaw:main
Recent Commits to openclaw:main
D
Darknet – Hacking Tools, Hacker News & Cyber Security
C
CERT Recently Published Vulnerability Notes
罗磊的独立博客
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
The Last Watchdog
The Last Watchdog
Attack and Defense Labs
Attack and Defense Labs
博客园 - 司徒正美
Help Net Security
Help Net Security
L
Lohrmann on Cybersecurity
人人都是产品经理
人人都是产品经理
Forbes - Security
Forbes - Security
Hacker News - Newest:
Hacker News - Newest: "LLM"
PCI Perspectives
PCI Perspectives
博客园 - 【当耐特】
T
Tor Project blog

博客园 - work hard work smart

使用 LangChain + Hugging Face 构建文本向量化服务 SQLAlchemy 使用详解 Python 中使用 Elasticsearch 的完整指南 Qdrant 向量数据库使用指南 OpenEvals 快速入门:LLM 评估指南 DeepEval 快速入门:LLM 应用评估指南 LangSmith 批量评估完全指南 Qwen-Agent 入门指南:快速构建智能体应用 LangSmith 集成实战:从追踪到评估的完整指南 初识 go-zero:一款让你写后端更规范、更高效的 Go 微服务框架 RAG 中为什么需要 Rerank,以及如何使用 Rerank LangChain4j RAG 核心组件与组合方式 如何使用 Elasticsearch 进行全文检索和向量检索 MinerU Docker 部署指南 5 分钟上手:为 Cline 配置一个免费的 MCP 天气服务 Neo4j 图数据库安装与 Spring Boot 集成实战指南 LangFuse 实战指南:用 @observe 三行代码给 LLM 应用加上全链路追踪 Function Call 深度解析:让大模型从"嘴炮"到"实干"的技术革命 Spring AI 提示词模板实战:告别硬编码,实现提示词工程化管理 LangChain4j 实战指南:用 Java 轻松构建 AI 应用 Spring AI 对话短期记忆实战:让大模型拥有"记忆力" Spring AI 提示词工程实战:让大模型更懂你的意图 Spring AI ChatClient 深度解析:优雅构建大模型应用的利器 Spring AI Alibaba DashScopeChatModel 实战 Spring 中 SSE 流式输出的多种实现方式详解 OpenSandbox 实战指南:为 AI Agent 构建安全的代码执行沙箱 在本机启动 LangGraph 开发服务器:完整指南 DeepAgents中Backend的奥秘:让AI Agent拥有文件操作能力 为什么选择 Go 开发 Web 接口?从入门到实践 智能搜索DeepAgent笔记 RAG学习笔记2--系统查询流程 RAG学习笔记1--系统文件导入流程 百炼 WebSearch 快速入门指南 Python 连接 MongoDB 完整指南:从连接配置到增删改查实战 一行命令搞定 MongoDB 开发环境:Docker Compose 部署 + 可视化管理 使用 Attu 可视化管理 Milvus 向量数据库 在 Windows Docker 中快速安装 Milvus 2.5.6 minio使用 Spark 集群搭建 hadoop集群安装 Windows 安装 OpenClaw 实战指南 MyBatis 核心流程和原理 Idea中安装Claude code插件 Spark 编程 使用Matplotlib 绘制直方图 Flink安装部署 Flume安装 查找导致cpu过高的代码方法 JVisualVM监控远程Java进程 jmap jacoco多模块生成java单元测试报告实践 arthas 使用demo LockSupport Exchanger CyclicBarrier CountDownLatch 手把手教你用python开始第一个机器学习项目
Spring AI Alibaba 入门实战
work hard work smart · 2026-03-13 · via 博客园 - work hard work smart

Spring AI Alibaba 入门实战:5 个示例带你快速上手

前言

很多开发者容易混淆 Spring Cloud AlibabaSpring AI Alibaba。简单来说:

  • Spring Cloud Alibaba:微服务架构解决方案(Nacos、Sentinel、Seata 等)
  • Spring AI Alibaba:AI 应用开发框架,基于 Spring AI,深度集成阿里云百炼平台

今天我们就通过一个完整的实战项目,详解 Spring AI Alibaba 的核心用法。

一、项目环境搭建

1.1 技术栈

  • JDK 21
  • Spring Boot 3.4.3
  • Spring AI 1.0.0
  • Spring AI Alibaba 1.0.0.3
  • 阿里云 DashScope(通义千问)

1.2 Maven 依赖配置

<properties>
    <java.version>21</java.version>
    <spring-ai.version>1.0.0</spring-ai.version>
    <spring-ai-alibaba.version>1.0.0.3</spring-ai-alibaba.version>
</properties>

<dependencyManagement>
    <dependencies>
        <!-- Spring AI BOM -->
        <dependency>
            <groupId>org.springframework.ai</groupId>
            <artifactId>spring-ai-bom</artifactId>
            <version>${spring-ai.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
        <!-- Spring AI Alibaba BOM -->
        <dependency>
            <groupId>com.alibaba.cloud.ai</groupId>
            <artifactId>spring-ai-alibaba-bom</artifactId>
            <version>${spring-ai-alibaba.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    
    <!-- 核心:DashScope 模型调用 -->
    <dependency>
        <groupId>com.alibaba.cloud.ai</groupId>
        <artifactId>spring-ai-alibaba-starter-dashscope</artifactId>
    </dependency>
</dependencies>

<repositories>
    <!-- Spring Milestones 仓库(必需) -->
    <repository>
        <id>spring-milestones</id>
        <url>https://repo.spring.io/milestone</url>
    </repository>
</repositories>

关键点说明:

  1. 必须使用 BOM:Spring AI Alibaba 通过 BOM 管理依赖版本,避免版本冲突
  2. 为什么是 dashscope:DashScope 是阿里云模型服务平台(通义千问等),该 starter 内置了客户端自动配置
  3. Spring Milestones 仓库:Spring AI 的部分版本还在 Milestone 阶段,必须配置此仓库

1.3 配置文件

spring.application.name=demo2
spring.ai.dashscope.api-key=你的 API_KEY
server.port=8080

获取 API Key:访问 https://dashscope.console.aliyun.com/ 注册并创建

二、5 个核心示例详解

示例 1:基础对话接口

代码实现:

@GetMapping("/chat")
public String chat(@RequestParam String message) {
    return chatClient.prompt()
            .user(message)
            .call()
            .content();
}

测试命令:

curl "http://localhost:8080/api/ai/chat?message=什么是 Spring AI"

原理:

  • ChatClient 是 Spring AI 的核心抽象,封装了与大模型的交互
  • .prompt() 创建提示词构建器
  • .user() 设置用户消息
  • .call() 同步调用模型
  • .content() 提取响应内容

示例 2:提示词工程(Prompt Engineering)

代码实现:

@PostMapping("/prompt/summary")
public PromptResponse promptSummary(@RequestBody ChatRequest request) {
    // 1. 角色设定 + 输出约束
    String systemPrompt = """
        你是资深 Java 技术讲师。
        你的输出必须满足:
        1) 使用中文;
        2) 先给 3 条核心要点;
        3) 再给 1 个简短示例;
        4) 总字数不超过 180 字。
        """;

    // 2. Few-shot 示例(少样本学习)
    String fewShotPrompt = """
        参考风格示例:
        问题:什么是缓存穿透?
        回答:
        - 查询的 key 不存在,导致请求直接打到数据库。
        - 高并发下会拖垮后端服务。
        - 常用布隆过滤器和空值缓存防护。
        示例:查询用户 ID=999999,缓存与数据库都不存在,系统缓存空对象 5 分钟。
        """;

    String response = chatClient.prompt()
            .system(systemPrompt)
            .user(fewShotPrompt + "\n\n现在请回答:" + request.message())
            .call()
            .content();

    return new PromptResponse(systemPrompt, response);
}

测试命令:

curl -X POST http://localhost:8080/api/ai/prompt/summary \
  -H "Content-Type: application/json" \
  -d '{"message": "Spring AI 是什么?"}'

核心技术点:

  1. System Prompt:设定 AI 的角色、语气、输出格式约束
  2. Few-shot Learning:提供示例让模型学习输出风格
  3. 结构化输出:通过明确的要求(3 条要点、1 个示例、180 字)控制输出质量

示例 3:流式响应(SSE)

代码实现:

/**
 * 流式响应(SSE - Server-Sent Events)
 * 使用 @GetMapping 的 produces 属性设置 Content-Type 为 text/event-stream
 * 配合 Flux 返回类型实现服务器主动推送
 */
@GetMapping(value = "/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<String> stream(@RequestParam String message) {
    return chatClient.prompt()
            .system("你是一个简洁的技术助手,分段输出,单段不超过 40 字。")
            .user(message)
            .stream()
            .content();
}

测试命令:

curl "http://localhost:8080/api/ai/stream?message=讲解一下 RAG 检索增强生成"

原理:

  • .stream() 替代 .call() 开启流式调用
  • 返回 Flux<String>(Reactor 响应式类型)
  • Spring WebFlux 自动将 Flux 转换为 SSE(Server-Sent Events)
  • 前端可以实时显示 AI 生成的每个 token

应用场景:

  • ChatGPT 式的打字机效果
  • 降低首字等待时间
  • 长文本生成的用户体验优化

示例 4:函数调用(Tool Calling)- 天气查询

Tool 组件:

@Component
public class DemoToolService {
    
    @Tool(description = "根据城市名称查询模拟天气信息")
    public String weather(
        @ToolParam(description = "城市名称,例如 Hangzhou 或 Beijing") String city
    ) {
        // 模拟天气数据
        String weather = WEATHER_DATA.getOrDefault(city.toLowerCase(), "多云,15-20C");
        return "城市:" + city + ",天气:" + weather;
    }
}

控制器调用:

@GetMapping("/tool/weather")
public ResponseEntity<?> toolWeather(@RequestParam String city) {
    String content = chatClient.prompt()
            .user("请查询%s的天气,并给出穿衣建议".formatted(city))
            .tools(demoToolService)  // 注册工具
            .call()
            .content();
    return ResponseEntity.ok(content);
}

测试命令:

curl "http://localhost:8080/api/ai/tool/weather?city=杭州"

工作原理(重点):

  1. 工具注册.tools(demoToolService) 扫描 @Tool 注解方法
  2. 模型决策:AI 分析用户问题,判断需要调用 weather 工具
  3. 参数提取:自动从对话中提取 city 参数
  4. 函数执行:Spring AI 调用 Java 方法
  5. 结果整合:将工具返回值交给模型生成最终回答

典型响应:

杭州今天小雨,8-14C,东风 2 级。建议穿薄毛衣或卫衣,搭配防风外套,出门记得带伞。

示例 5:函数调用 - 汇率换算

Tool 组件:

@Tool(description = "根据币种和金额进行模拟汇率换算")
public String currencyExchange(
    @ToolParam(description = "源币种,例如 CNY") String from,
    @ToolParam(description = "目标币种,例如 USD") String to,
    @ToolParam(description = "金额,例如 100") Double amount
) {
    // 汇率计算逻辑
    double amountInCny = sourceAmount * fromRate;
    double targetAmount = amountInCny / toRate;
    return String.format("换算结果:%.2f %s = %.2f %s", sourceAmount, fromCode, targetAmount, toCode);
}

控制器调用:

@GetMapping("/tool/fx")
public ResponseEntity<?> toolFx(
    @RequestParam String from,
    @RequestParam String to,
    @RequestParam Double amount
) {
    String content = chatClient.prompt()
            .user("把%s %.2f 换算成 %s,并解释汇率计算过程".formatted(from, amount, to))
            .tools(demoToolService)
            .call()
            .content();
    return ResponseEntity.ok(content);
}

测试命令:

curl "http://localhost:8080/api/ai/tool/fx?from=CNY&to=USD&amount=100"

响应示例:

100 CNY = 13.89 USD。计算过程:先将 100 CNY 按 1:1 折算为 100 CNY,再除以 USD 对 CNY 汇率 7.20,得到 13.89 USD。

三、核心原理深度解析

3.1 ChatClient 自动配置

当你引入 spring-ai-alibaba-starter-dashscope 后,Spring Boot 自动配置机制会:

  1. 创建 DashScopeApi 实例:读取 spring.ai.dashscope.api-key 配置
  2. 注册 ChatModel Bean:DashScope 的聊天模型实现
  3. 注入 ChatClient.Builder:通过构造函数注入到控制器
// Spring AI 内部伪代码
@Configuration
@ConditionalOnProperty("spring.ai.dashscope.api-key")
public class DashScopeAutoConfiguration {
    
    @Bean
    public DashScopeApi dashScopeApi(String apiKey) {
        return new DashScopeApi(apiKey);
    }
    
    @Bean
    public ChatModel dashScopeChatModel(DashScopeApi api) {
        return new DashScopeChatModel(api);
    }
}

3.2 Tool Calling 的实现机制

步骤 1:工具元数据提取

  • Spring AI 扫描 @Component 类中的 @Tool 注解方法
  • 提取方法签名、参数描述(@ToolParam)、功能说明
  • 生成 JSON Schema 格式的工具定义

步骤 2:工具定义发送给模型

{
  "name": "weather",
  "description": "根据城市名称查询模拟天气信息",
  "parameters": {
    "type": "object",
    "properties": {
      "city": {
        "type": "string",
        "description": "城市名称,例如 Hangzhou 或 Beijing"
      }
    },
    "required": ["city"]
  }
}

步骤 3:模型决策与回调

  • 模型分析用户问题,决定调用哪个工具
  • 返回工具名称和参数(如 {"name": "weather", "arguments": {"city": "杭州"}}
  • Spring AI 找到对应 Java 方法并执行
  • 将执行结果返回给模型生成自然语言回答

3.3 流式响应的底层原理

传统调用(.call()):

用户请求 → 等待完整响应 → 返回结果
(延迟高,用户体验差)

流式调用(.stream()):

用户请求 → Token 1 → Token 2 → Token 3 → ... → 完成
        (实时推送,打字机效果)

技术栈:

  • Reactor ProjectFlux<T> 响应式编程
  • SSE(Server-Sent Events):HTTP 长连接,服务器主动推送
  • WebFlux:Spring 响应式 Web 框架

四、常见问题与避坑指南

Q1:为什么不能直接用 spring-ai-alibaba-starter?

答:

  • starter-dashscope 是专门针对 DashScope 模型的客户端
  • starter 是聚合包,可能包含不需要的模块
  • 精确引入依赖可以避免版本冲突和打包体积过大

Q2:依赖下载失败怎么办?

解决方案:

<!-- 1. 确保配置 Spring Milestones 仓库 -->
<repository>
    <id>spring-milestones</id>
    <url>https://repo.spring.io/milestone</url>
</repository>

<!-- 2. 如果使用国内网络,可添加阿里云镜像 -->
<mirror>
    <id>aliyun</id>
    <mirrorOf>central,spring-milestones</mirrorOf>
    <url>https://maven.aliyun.com/repository/public</url>
</mirror>

Q3:JDK 版本要求?

答: 必须 JDK 17+,推荐 JDK 21(本项目使用 21)

Q4:如何切换到其他大模型(如 Ollama、OpenAI)?

答案: 只需更换 starter 依赖和配置:

<!-- OpenAI -->
<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-openai-spring-boot-starter</artifactId>
</dependency>

<!-- Ollama(本地部署) -->
<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-ollama-spring-boot-starter</artifactId>
</dependency>

五、扩展阅读与进阶方向

5.1 更多 Starter 模块

  • spring-ai-alibaba-graph-core:多智能体工作流
  • spring-ai-alibaba-starter-nacos-mcp-client:Nacos MCP 客户端
  • spring-ai-alibaba-starter-nl2sql:自然语言转 SQL

5.2 生产级实践建议

  1. 错误处理:添加重试机制和降级策略
  2. 限流保护:防止 API 调用超限
  3. 日志记录:记录 prompt 和 response 便于调试
  4. 成本控制:监控 token 使用量

5.3 下一步学习路线

  1. RAG(检索增强生成)+ 向量数据库
  2. Function Calling 高级用法(多工具协同)
  3. Agent 智能体开发
  4. 私有化模型部署(Ollama + Spring AI)

总结

本文通过 5 个实用示例,带你掌握了 Spring AI Alibaba 的核心能力:

示例 技术点 适用场景
基础对话 ChatClient 基础用法 简单问答
提示词工程 System Prompt + Few-shot 结构化输出
流式响应 SSE + Reactor 实时聊天界面
天气查询 Tool Calling 单参数 外部数据集成
汇率换算 Tool Calling 多参数 复杂业务计算

核心优势:

  • ✅ 零学习成本(Spring 开发者友好)
  • ✅ 自动配置(约定优于配置)
  • ✅ 类型安全(Java 强类型检查)
  • ✅ 易于测试(标准 Bean 管理)

现在你已经具备了开发 AI 应用的基础能力,快去尝试构建自己的智能助手吧!


参考资料: