跳到主要内容
Spring AI 实战:Java 原生接入大模型快速上手 | 极客日志
Java AI java
Spring AI 实战:Java 原生接入大模型快速上手 Spring AI 是专为 Java 生态设计的原生 AI 框架,通过统一接口屏蔽底层模型差异。本文详解其核心特性,包括多供应商适配、标准化 API、Spring Boot 集成及 RAG 支持。实战部分演示了基于 DeepSeek 模型的对话功能搭建,涵盖环境配置、依赖引入、控制器编写及流式响应优化。最终结合可视化界面,实现了完整的 AI 聊天应用流程,帮助开发者快速在 Java 项目中落地大模型能力。
PgDevote 发布于 2026/3/27 0 浏览Spring AI 实战:Java 原生接入大模型快速上手
在大模型席卷全球的技术浪潮下,Java 开发者们迫切需要一款贴合自身生态、低门槛接入 AI 能力的框架。Spring AI 的出现,恰好填补了这一空白 —— 它并非简单移植 Python 生态的现有方案,而是深度遵循 Spring 设计哲学,为 Java 和 Spring 开发者打造了原生的 AI 开发框架。
一、什么是 Spring AI?
Spring AI 是面向 Java 和 Spring 生态的原生人工智能框架,其核心设计理念完全传承自 Spring:依赖注入、POJO 编程、模块化架构与可配置性。它重构了 AI 应用的全开发流程,让开发者无需关注底层模型的适配细节,就能像调用数据库、Web API 一样轻松集成聊天、文本嵌入、图像生成、语音处理等 AI 能力。
更重要的是,Spring AI 完美解决了多 AI 供应商适配的痛点 —— 通过'一套接口,多种实现'的统一抽象,开发者可以无缝切换 OpenAI、Anthropic、Bedrock、Hugging Face、Vertex AI、Ollama 等主流 AI 服务,无需修改核心业务代码。同时,它还支持企业内部数据与 AI 模型的快速关联,这正是检索增强生成(RAG)等高级场景的核心需求。
参考资源
二、Spring AI 核心特性:为什么值得选?
Spring AI 覆盖了 AI 应用开发的全流程,其核心特性可以总结为以下 7 点,每一点都精准命中开发者的实际需求:
1. 全栈多供应商模型适配,覆盖主流 AI 能力
深度对接 Anthropic、OpenAI 等主流服务商,覆盖聊天交互、文本嵌入、多模态生成、语音交互、内容安全等核心能力。
聊天交互 :文本对话、多轮上下文对话
文本嵌入 :语义向量转换,支撑语义搜索
多模态生成 :文生图、图生文
语音交互 :音频转录/语音转文字、文本转语音
内容安全 :敏感信息检测与审核
所有模型统一接口封装,切换模型无需修改业务代码,提升项目灵活性与可扩展性。
2. 标准化抽象 API,统一调用体验
Spring AI 提供了 ChatClient、EmbeddingModel、ImageModel 等标准化接口,开发者无需关心底层模型的差异。支持同步/流式调用及模型高级功能(如 OpenAI Function Calling),聚焦业务逻辑,提升开发效率。
3. 原生集成 Spring Boot,开箱即用
遵循 Spring Boot 设计理念,通过 Starter 依赖与自动装配实现 AI 组件一键集成,Spring Initializr 可快速生成项目骨架,开箱即用,贴合 Java 开发者习惯。
4. 结构化输出与类型安全,降低维护成本
支持将 AI 非结构化响应自动解析映射到 Java POJO,保障类型安全,避免繁琐的字符串解析与类型转换,降低维护成本。
5. 内置向量存储与 RAG 支持,激活私有知识库 Spring AI 集成了 PostgreSQL/pgvector、Pinecone、Qdrant、Redis、Weaviate 等主流向量数据库,提供元数据过滤、相似度检索能力;同时内置 ETL 流程,可快速搭建 RAG 系统,解决大模型'知识过期''不懂私有数据'痛点。
6. 工具调用能力,打通业务系统闭环 原生支持模型驱动的工具调用,可将 Spring Bean 注册为 AI 可调用工具,实现 AI 自动调用业务接口、查询数据库等操作,例如:
调用天气 API 获取实时气象数据
查询企业 CRM 系统获取客户详情
执行业务数据统计与分析操作
实现 AI 与业务流程深度融合,让 AI 从'对话工具'升级为'业务智能入口',打通需求到执行的全闭环。
三、快速上手:环境准备与 Deepseek 对话案例 光看理论不够,咱们直接动手做个 Demo。下面我们将通过一个完整的案例,教大家搭建 Spring AI 环境,并实现与 Deepseek 模型的对话交互。
3.1 环境要求 Spring AI 构建在 Spring Boot 3.x 之上,对环境有明确要求:
JDK :必须为 17 及以上版本(不支持 Java 8/11/16)
Maven :3.6 及以上版本
Spring Boot :3.x 系列(本文使用 3.5.0 版本)
3.2 创建 Spring Boot 项目
Name:Weiz-SpringAI-QuickStart
Group:com.example
Artifact:Weiz-SpringAI-QuickStart
Package name:com.example.weizspringai
Language:Java
JDK:17
Spring Boot:3.5.3
Packaging:Jar
接着,Spring Boot 版本选择 3.5.x,依赖仅需添加「Spring Web」依赖(后续通过 Maven 引入 Spring AI 相关依赖)。
Weiz-SpringAI-QuickStart/
├── src /
│ ├── main /
│ │ ├── java/
│ │ │ └── com/
│ │ │ └── example/
│ │ │ └── weizspringai/
│ │ │ └── WeizSpringAiQuickStartApplication.java
│ │ └── resources/
│ │ └── application.properties
│ └── test/
└── pom.xml
3.3 配置 pom.xml 依赖 在 pom.xml 中添加 Spring AI 相关依赖,核心是导入 Spring AI BOM 统一管理版本,并引入 Deepseek 模型 starter:
<?xml version="1.0" encoding="UTF-8" ?>
<project xmlns ="http://maven.apache.org/POM/4.0.0"
xmlns:xsi ="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation ="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd" >
<modelVersion > 4.0.0</modelVersion >
<parent >
<groupId > com.example</groupId >
<artifactId > Weiz-SpringAI</artifactId >
<version > 0.0.1-SNAPSHOT</version >
</parent >
<artifactId > Weiz-SpringAI-QuickStart</artifactId >
<name > Weiz-SpringAI-QuickStart</name >
<description > Weiz-SpringAI-QuickStart</description >
<properties >
<java.version > 17</java.version >
<maven.compiler.source > 17</maven.compiler.source >
<maven.compiler.target > 17</maven.compiler.target >
</properties >
<dependencies >
<dependency >
<groupId > org.springframework.boot</groupId >
<artifactId > spring-boot-starter-webflux</artifactId >
</dependency >
<dependency >
<groupId > org.springframework.boot</groupId >
<artifactId > spring-boot-starter-web</artifactId >
</dependency >
<dependency >
<groupId > org.springframework.ai</groupId >
<artifactId > spring-ai-starter-model-deepseek</artifactId >
</dependency >
<dependency >
<groupId > org.springframework.boot</groupId >
<artifactId > spring-boot-starter-test</artifactId >
<scope > test</scope >
</dependency >
</dependencies >
<build >
<plugins >
<plugin >
<groupId > org.springframework.boot</groupId >
<artifactId > spring-boot-maven-plugin</artifactId >
</plugin >
</plugins >
</build >
</project >
3.4 配置 application.properties 在 src/main/resources/application.properties 中配置 Deepseek 模型的基础信息:
spring.application.name=Weiz-SpringAI-QuickStart
server.port=8080
# Deepseek URL
spring.ai.deepseek.base-url=https://api.deepseek.com
spring.ai.deepseek.api-key=你的 Deepseek appkey
spring.ai.deepseek.chat.options.model=deepseek-chat
注意:Deepseek API 密钥需要在 Deepseek 官网注册获取,替换配置中的占位符。
3.5 编写 ChatController 创建 com.example.weizspringai.controller 包,并编写 ChatController 类,实现与 Deepseek 模型的交互:
import org.springframework.ai.deepseek.DeepSeekChatModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/ai")
public class ChatController {
@Autowired
private DeepSeekChatModel chatModel;
@PostMapping("/chat")
public String chat (@RequestBody String message) {
String resp = chatModel.call(message);
return resp;
}
}
这里简化了返回类型,实际生产中可根据需要定义 DTO。
3.6 启动并测试
四、实战进阶:流式响应与可视化界面优化 前面使用 Spring AI 快速整合 DeepSeek,实现了与大模型对话的功能,但是这个项目存在两个不足:无可视化交互界面;AI 响应为一次性返回,缺乏实时感。下面对项目进行优化升级。
Step 1:实现流式返回接口 在 ChatController 中,创建新接口 /ai/chatStream 接口,利用 SSE 技术实现流式传输。
@PostMapping("/chatStream")
public SseEmitter chatStream (@RequestBody String message) {
SseEmitter emitter = new SseEmitter (Long.MAX_VALUE);
Flux<String> stream = chatModel.stream(message);
stream.subscribe(
chunk -> {
try {
String json = objectMapper.writeValueAsString(chunk);
emitter.send(SseEmitter.event().data(json).build());
} catch (IOException e) {
emitter.completeWithError(e);
}
},
error -> { emitter.completeWithError(error); },
() -> { emitter.complete(); }
);
return emitter;
}
Step 2:创建可视化聊天界面 为了更直观地与模型交互,我们可以在 src/main/resources/static 目录下创建 index.html,实现简单的聊天界面。
<!DOCTYPE html >
<html lang ="zh-CN" >
<head >
<meta charset ="UTF-8" >
<meta name ="viewport" content ="width=device-width, initial-scale=1.0" >
<title > AI 聊天助手(流式响应)</title >
<style >
* { margin :0 ; padding :0 ; box-sizing : border-box; }
body { font-family :-apple-system,BlinkMacSystemFont,"Segoe UI" ,Roboto,"Helvetica Neue" ,Arial, sans-serif; background : linear-gradient (135deg , #667eea 0% , #764ba2 100% ); height :100vh ; display : flex; justify-content : center; align-items : center; }
.chat-container { width :800px ; height :600px ; background : white; border-radius :16px ; box-shadow :0 20px 60px rgba (0 ,0 ,0 ,0.3 ); display : flex; flex-direction : column; overflow : hidden; }
.chat-header { background : linear-gradient (135deg , #667eea 0% , #764ba2 100% ); padding :20px ; color : white; }
.chat-header h1 { font-size :24px ; font-weight :600 ; }
.chat-messages { flex :1 ; padding :20px ; overflow-y : auto; background : #f5f5f5 ; }
.message { margin-bottom :16px ; display : flex; align-items : flex-start; }
.message .user { justify-content : flex-end; }
.message .assistant { justify-content : flex-start; }
.message-content { max-width :70% ; padding :12px 16px ; border-radius :12px ; line-height :1.5 ; word-wrap :break-word; }
.message .user .message-content { background : linear-gradient (135deg , #667eea 0% , #764ba2 100% ); color : white; border-bottom-right-radius :4px ; }
.message .assistant .message-content { background : white; color : #333 ; border-bottom-left-radius :4px ; box-shadow :0 2px 8px rgba (0 ,0 ,0 ,0.1 ); }
.chat-input-container { padding :20px ; background : white; border-top :1px solid #e0e0e0 ; }
.chat-input-form { display : flex; gap :12px ; }
#messageInput { flex :1 ; padding :12px 16px ; border :2px solid #e0e0e0 ; border-radius :24px ; font-size :16px ; outline : none; transition : border-color 0.3s ; }
#sendButton { padding :12px 32px ; background : linear-gradient (135deg , #667eea 0% , #764ba2 100% ); color : white; border : none; border-radius :24px ; font-size :16px ; font-weight :600 ; cursor : pointer; }
</style >
</head >
<body >
<div class ="chat-container" >
<div class ="chat-header" > <h1 > AI 聊天助手</h1 > <p > 基于 Spring AI 和 DeepSeek 的智能对话系统(流式响应)</p > </div >
<div class ="chat-messages" id ="chatMessages" > </div >
<div class ="chat-input-container" >
<form class ="chat-input-form" id ="chatForm" >
<input type ="text" id ="messageInput" placeholder ="输入您的问题..." autocomplete ="off" required >
<button type ="submit" id ="sendButton" > 发送</button >
</form >
</div >
</div >
<script >
const chatMessages = document .getElementById ('chatMessages' );
const chatForm = document .getElementById ('chatForm' );
const messageInput = document .getElementById ('messageInput' );
const sendButton = document .getElementById ('sendButton' );
async function sendMessage (message ){
const response = await fetch ('/ai/chatStream' , {
method : 'POST' ,
headers : { 'Content-Type' : 'application/json' },
body : JSON .stringify ({ message : message })
});
if (!response.ok ) throw new Error ('网络请求失败' );
const reader = response.body .getReader ();
const decoder = new TextDecoder ();
let fullText = '' ;
while (true ) {
const { done, value } = await reader.read ();
if (done) ;
chunk = decoder. (value, { : });
lines = chunk. ( ). ( line. ());
( line lines) {
{
cleanLine = line. ( , ). ();
(!cleanLine) ;
data = . (cleanLine);
(data. ) { fullText += data. ; }
} (e) { . ( , e); }
}
}
}
chatForm. ( , (e) => {
e. ();
message = messageInput. . ();
(!message) ;
messageInput. = ;
(message);
});
</script >
</body >
</html >
Step 3:启动并测试
总结 总的来说,Spring AI 让 Java 接入 AI 变得像调用普通服务一样简单。通过统一抽象接口,我们无需跨生态就能快速集成大模型能力。从环境搭建到流式响应优化,整个流程展示了如何在现有 Java 项目中平滑落地 AI 功能,极大降低了开发门槛。
break
const
decode
stream
true
const
split
'\n'
filter
line =>
trim
for
const
of
try
const
replace
/^data:\s*/
''
trim
if
continue
const
JSON
parse
if
response
response
catch
console
warn
'解析 JSON 失败:'
addEventListener
'submit'
async
preventDefault
const
value
trim
if
return
value
''
await
sendMessage
相关免费在线工具 Keycode 信息 查找任何按下的键的javascript键代码、代码、位置和修饰符。 在线工具,Keycode 信息在线工具,online
Escape 与 Native 编解码 JavaScript 字符串转义/反转义;Java 风格 \uXXXX(Native2Ascii)编码与解码。 在线工具,Escape 与 Native 编解码在线工具,online
JavaScript / HTML 格式化 使用 Prettier 在浏览器内格式化 JavaScript 或 HTML 片段。 在线工具,JavaScript / HTML 格式化在线工具,online
JavaScript 压缩与混淆 Terser 压缩、变量名混淆,或 javascript-obfuscator 高强度混淆(体积会增大)。 在线工具,JavaScript 压缩与混淆在线工具,online
RSA密钥对生成器 生成新的随机RSA私钥和公钥pem证书。 在线工具,RSA密钥对生成器在线工具,online
Mermaid 预览与可视化编辑 基于 Mermaid.js 实时预览流程图、时序图等图表,支持源码编辑与即时渲染。 在线工具,Mermaid 预览与可视化编辑在线工具,online