Spring AI 入门指南:从零开始构建你的第一个 AI 应用
系列说明:本文为《Spring AI 实战系列 入门篇》第 1 篇,聚焦核心概念与快速上手
学习目标:掌握 Spring AI 核心概念(Model、Prompt、Embedding),并创建你的第一个 AI 项目
预计阅读时间:15 分钟
📖 目录
一、Spring AI 是什么?
Spring AI 是 Spring 官方推出的 AI 集成框架,简化 AI 应用开发。
核心理念
连接企业数据与 APIs 与 AI 模型
解决什么问题?
开发 AI 应用时,每个模型、每个向量数据库都有不同的 API。Spring AI 提供了统一抽象层:
┌─────────────────────────────────────────────┐
│ 你的应用代码 │
├─────────────────────────────────────────────┤
│ Spring AI 统一 API │
│ ChatClient │ Embedding │ VectorStore │ Tools │
├─────────────────────────────────────────────┤
│ 具体实现 │
│ OpenAI │ Anthropic │ 阿里 │ 百度 │ ... │
└─────────────────────────────────────────────┘
核心优势
- ✅ 零改动切换模型 —— OpenAI ↔ Claude ↔ 通义千问,改配置即可
- ✅ Spring 生态完美融合 —— 自动配置、依赖注入、starter 组件
- ✅ 开箱即用 —— 20+ 向量数据库、10+ AI 提供商
二、核心概念速览
💡 提示:理解这三个概念,是掌握 Spring AI 的基础。
2.1 AI Model:AI 的大脑
定义:AI 模型是经过训练的算法,能根据输入生成输出。
类比:厨师 需要学习菜谱才能做菜,AI 模型 需要训练才能变得智能。
支持的模型类型
| 类型 | 输入 → 输出 | 场景 |
|---|---|---|
| Chat | 文本 → 文本 | 对话、问答 |
| Embedding | 文本 → 向量 | 语义搜索、RAG |
| Image | 文本 → 图片 | AI 绘画 |
| Audio | 音频 → 文本 | 语音转写 |
支持的 AI 提供商
🌍 国外主流:
| 提供商 | 代表模型 | 特点 |
|---|---|---|
| OpenAI | GPT-4, GPT-3.5 | 行业标杆 |
| Anthropic | Claude 3 | 安全性强 |
| Gemini, PaLM | 谷歌生态 | |
| Meta | Llama 3 | 开源免费 |
| Mistral | Mistral, Mixtral | 欧洲最强 |
🇨🇳 国内热门:
| 提供商 | 代表模型 | 特点 |
|---|---|---|
| 阿里云 | 通义千问 (Qwen)、Qwen2 | 中文强、开源可本地部署 |
| 百度 | 文心一言 (ERNIE Bot) | 中文理解强、企业友好 |
| 智谱 AI | GLM-4 (ChatGLM) | 国产开源、性能优秀 |
| 腾讯 | 混元 (Hunyuan) | 腾讯生态集成 |
| 字节跳动 | 豆包 (Doubao) | 性价比高 |
| 月之暗面 | Kimi (Moonshot) | 长上下文支持 |
📱 本地运行:
| 工具 | 说明 |
|---|---|
| Ollama | 主流本地 LLM 运行工具 |
| vLLM | 高性能推理引擎 |
Spring AI 配置示例
OpenAI (GPT-4):
spring.ai.openai.api-key=${OPENAI_API_KEY}
spring.ai.openai.chat.options.model=gpt-4
通义千问 (阿里云):
spring.ai.dashscope.api-key=${DASHSCOPE_API_KEY}
spring.ai.dashscope.chat.options.model=qwen-turbo
智谱 GLM:
spring.ai.zhipu.api-key=${ZHIPU_API_KEY}
spring.ai.zhipu.chat.options.model=glm-4
Ollama (本地):
spring.ai.ollama.base-url=http://localhost:11434
spring.ai.ollama.chat.options.model=llama3
模型关键参数
public class ChatOptions {
String model; // 模型名称
Float temperature; // 随机性:0.0-2.0
Integer maxTokens; // 最大输出长度
}
| 参数 | 作用 | 推荐值 |
|---|---|---|
temperature | 控制创意性:低=确定,高=创意 | 0.7(通用)/ 0.2(精确)/ 1.5+(创意) |
maxTokens | 限制输出长度 | 按需设置 |
2.2 Prompt:与 AI 沟通的语言
Prompt = 你对 AI 说的话,但它是种沟通协议,不是普通文字。
对比传统编程 vs AI 编程
传统编程:指令 → 计算机执行
AI 编程:Prompt → AI 理解 → 生成回应
Prompt 的结构
Prompt prompt = new Prompt(
List.of(
new SystemMessage("你是一个专业律师"), // 角色设定
new UserMessage("什么是合同?") // 用户问题
),
ChatOptions.builder()
.temperature(0.7)
.build()
);
消息类型:
| 角色 | 作用 | 示例 |
|---|---|---|
SYSTEM | 定义 AI 身份 | "你是一个友好的客服" |
USER | 用户输入 | "我想退货" |
ASSISTANT | AI 回复 | "请问订单号是?" |
TOOL | 工具结果 | "当前温度:25°C" |
Prompt Template(模板)
使用 {变量} 定义模板,运行时替换:
// Spring AI 中使用
chatClient.prompt()
.user(u -> u
.text("写一首关于 {theme} 的诗")
.param("theme", "春天"))
.call()
.content();
Prompt Engineering(提示工程)
研究表明,好的 Prompt 能大幅提升效果:
❌ 低效:"写一首诗"
✅ 高效:"请用七言绝句,写一首关于春天的诗,押韵工整"
🔑 技巧:"Take a deep breath and work on this step by step."
2.3 Embedding:让机器读懂语义
Embedding = 将文本转为数字向量
"猫" → [0.23, -0.45, 0.89, ...] (1536维)
"狗" → [0.25, -0.42, 0.85, ...] (相似!)
"汽车" → [-0.78, 0.34, -0.12, ...] (不同)
核心洞察:语义相似的文本 → 向量距离近
搜索对比
| 方式 | 原理 | 效果 |
|---|---|---|
| 关键词搜索 | 匹配"苹果" | 手机/水果混淆 |
| Embedding 搜索 | 语义理解 | "水果"能找到"苹果" |
在 RAG 中的应用
用户问题 → Embedding → 向量数据库检索 → 构建提示词 → AI 生成回答
// Spring AI 中的 Embedding
float[] vector = embeddingModel.embed("Hello world");
int dimensions = embeddingModel.dimensions(); // 如 1536
三、创建第一个 Spring AI 项目
3.1 环境要求
| 要求 | 版本 |
|---|---|
| Java | 17+ |
| Spring Boot | 3.4.x 或 3.5.x |
| Maven | 3.8+ |
3.2 快速创建
方式一:start.spring.io
- 访问 start.spring.io/
- 选择 Maven、Java 21、Spring Boot 3.4+
- 添加依赖:Spring Web、Spring AI
- 下载并解压
方式二:手动创建
1. 创建目录结构:
demo/
├── pom.xml
└── src/main/
├── java/com/example/demo/
│ └── DemoApplication.java
└── resources/
└── application.properties
2. pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.4.0</version>
</parent>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<!-- Spring AI BOM -->
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-bom</artifactId>
<version>1.1.3</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- OpenAI 模型 -->
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-model-openai</artifactId>
</dependency>
</dependencies>
</project>
3. application.properties:
# OpenAI(美国)
spring.ai.openai.api-key=${OPENAI_API_KEY}
# 或使用通义千问(国内)
# spring.ai.dashscope.api-key=${DASHSCOPE_API_KEY}
spring.ai.openai.chat.options.model=gpt-4o-mini
spring.ai.openai.chat.options.temperature=0.7
4. 启动类:
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
四、实战代码
4.1 AI 控制器
创建 controller/AIController.java:
package com.example.demo.controller;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/ai")
public class AIController {
private final ChatClient chatClient;
public AIController(ChatClient.Builder builder) {
this.chatClient = builder.build();
}
/** 基础对话 */
@GetMapping("/chat")
public String chat(@RequestParam String message) {
return chatClient.prompt()
.user(message)
.call()
.content();
}
/** 带角色设定 */
@GetMapping("/expert")
public String expert(@RequestParam String message) {
return chatClient.prompt()
.system("你是一位资深 Java 架构师")
.user(message)
.call()
.content();
}
/** 模板参数 */
@GetMapping("/poem")
public String poem(@RequestParam String theme) {
return chatClient.prompt()
.user(u -> u
.text("请用七言绝句,写一首关于 {theme} 的诗")
.param("theme", theme))
.call()
.content();
}
}
4.2 启动与测试
# 设置 API Key
set OPENAI_API_KEY=sk-your-key-here
# 启动项目
mvn spring-boot:run
测试接口:
curl "http://localhost:8080/ai/chat?message=你好"
curl "http://localhost:8080/ai/poem?theme=春天"
五、常见问题
Q1: 报 "ApiKey is missing"
# 设置环境变量
export OPENAI_API_KEY=sk-xxxxx
Q2: 依赖下载慢
在 pom.xml 添加国内镜像:
<repositories>
<repository>
<id>aliyun</id>
<url>https://maven.aliyun.com/repository/public</url>
</repository>
</repositories>
Q3: 国内模型推荐
| 模型 | 获取地址 | 免费额度 |
|---|---|---|
| 通义千问 | qwen.cloud.alibaba.com/ | 有免费额度 |
| 智谱 GLM | open.bigmodel.cn/ | 有免费额度 |
| 百度文心 | console.bce.baidu.com/ | 企业版 |
六、系列预告
本文为《Spring AI 实战系列 入门篇》第 1 篇。
完整系列规划:
| 篇目 | 内容 | 状态 |
|---|---|---|
| 第 1 篇 | 核心概念 + 快速上手 | ✅ 本文 |
| 第 2 篇 | Tool Calling:让 AI 调用外部函数 | 🔜 即将发布 |
| 第 3 篇 | VectorStore + RAG:构建私有知识库 | 🔜 即将发布 |
| 第 4 篇 | 结构化输出:AI 结果映射为 POJO | 🔜 即将发布 |
| 第 5 篇 | Advisors:自定义 AI 中间件 | 🔜 即将发布 |
| 第 6 篇 | 多模型切换与国产模型集成 | 🔜 即将发布 |
七、参考资料
官方文档
-
Spring AI Official Reference
- 网址:docs.spring.io/spring-ai/r…
- 内容:Spring AI 官方文档首页,包含完整 API 参考
-
Spring AI GitHub
- 网址:github.com/spring-proj…
- 内容:Spring AI 源代码与示例项目
-
Spring Initializr
- 网址:start.spring.io/
- 内容:Spring 项目初始化工具
国内模型文档
-
阿里云通义千问 (DashScope)
- 网址:help.aliyun.com/zh/dashscop…
- Spring AI 集成:docs.spring.io/spring-ai/r…
-
智谱 AI (GLM)
- 网址:open.bigmodel.cn/
- API 文档:open.bigmodel.cn/dev/api
-
百度文心一言 (ERNIE)
- 网址:console.bce.baidu.com/wenxin/
- Spring AI 集成指南
-
Ollama (本地模型)
- 网址:ollama.com/
- Spring AI 集成:docs.spring.io/spring-ai/r…
学习资源
-
Spring AI Samples
- 网址:github.com/spring-ai-c…
- 内容:Spring AI 示例项目汇总
-
OpenAI API Documentation
- 网址:platform.openai.com/docs
- 内容:GPT 模型 API 参考
-
Prompt Engineering Guide
- 网址:www.promptingguide.ai/
- 内容:提示工程最佳实践
📌 引用说明:本文核心概念与技术描述参考自 Spring AI 官方文档(docs.spring.io/spring-ai/r…
系列:《Spring AI 实战系列 入门篇》第 1 篇(共 6 篇)