

























很多开发者容易混淆 Spring Cloud Alibaba 和 Spring AI Alibaba。简单来说:
今天我们就通过一个完整的实战项目,详解 Spring AI Alibaba 的核心用法。
<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>
关键点说明:
spring.application.name=demo2
spring.ai.dashscope.api-key=你的 API_KEY
server.port=8080
获取 API Key:访问 https://dashscope.console.aliyun.com/ 注册并创建
代码实现:
@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() 提取响应内容代码实现:
@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 是什么?"}'
核心技术点:
代码实现:
/**
* 流式响应(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 响应式类型)应用场景:
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=杭州"
工作原理(重点):
.tools(demoToolService) 扫描 @Tool 注解方法典型响应:
杭州今天小雨,8-14C,东风 2 级。建议穿薄毛衣或卫衣,搭配防风外套,出门记得带伞。
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。
当你引入 spring-ai-alibaba-starter-dashscope 后,Spring Boot 自动配置机制会:
spring.ai.dashscope.api-key 配置// 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);
}
}
步骤 1:工具元数据提取
@Component 类中的 @Tool 注解方法@ToolParam)、功能说明步骤 2:工具定义发送给模型
{
"name": "weather",
"description": "根据城市名称查询模拟天气信息",
"parameters": {
"type": "object",
"properties": {
"city": {
"type": "string",
"description": "城市名称,例如 Hangzhou 或 Beijing"
}
},
"required": ["city"]
}
}
步骤 3:模型决策与回调
{"name": "weather", "arguments": {"city": "杭州"}})传统调用(.call()):
用户请求 → 等待完整响应 → 返回结果
(延迟高,用户体验差)
流式调用(.stream()):
用户请求 → Token 1 → Token 2 → Token 3 → ... → 完成
(实时推送,打字机效果)
技术栈:
Flux<T> 响应式编程答:
starter-dashscope 是专门针对 DashScope 模型的客户端starter 是聚合包,可能包含不需要的模块解决方案:
<!-- 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>
答: 必须 JDK 17+,推荐 JDK 21(本项目使用 21)
答案: 只需更换 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>
spring-ai-alibaba-graph-core:多智能体工作流spring-ai-alibaba-starter-nacos-mcp-client:Nacos MCP 客户端spring-ai-alibaba-starter-nl2sql:自然语言转 SQL本文通过 5 个实用示例,带你掌握了 Spring AI Alibaba 的核心能力:
| 示例 | 技术点 | 适用场景 |
|---|---|---|
| 基础对话 | ChatClient 基础用法 | 简单问答 |
| 提示词工程 | System Prompt + Few-shot | 结构化输出 |
| 流式响应 | SSE + Reactor | 实时聊天界面 |
| 天气查询 | Tool Calling 单参数 | 外部数据集成 |
| 汇率换算 | Tool Calling 多参数 | 复杂业务计算 |
核心优势:
现在你已经具备了开发 AI 应用的基础能力,快去尝试构建自己的智能助手吧!
参考资料:
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。