尧图网络 高端网站定制 · 原创设计
免费咨询热线
400-888-6620
免费获取方案
Spring AI 接入 DeepSeek Chat 模型
本文介绍如何在 Spring Boot 项目中使用 Spring AI 接入 DeepSeek Chat 模型实现一个简单的对话接口。示例包含 Maven 依赖、application.yml配置、ChatClient调用代码以及常见问题排查。示例基于当前 Spring AI 2.0.x 的自动配置方式。Spring AI 和 DeepSeek 的模型名称会随版本变化实际使用时请以对应版本的官方文档为准。一、准备工作开始之前需要准备JDK 17 或更高版本Maven 3.9一个 Spring Boot 项目一个 DeepSeek API Key。DeepSeek API Key 可以在 DeepSeek API Keys 页面 创建。不要把 API Key 直接提交到 Git 仓库。推荐通过环境变量、配置中心或密钥管理服务注入。二、创建项目并添加 Maven 依赖下面给出一个完整的pom.xml关键配置。Spring AI 官方当前稳定版本为 2.0.x示例使用2.0.0BOM如果项目使用其他 Spring AI 版本只需要将 BOM 版本替换为项目实际版本。?xml version1.0 encodingUTF-8?projectxmlnshttp://maven.apache.org/POM/4.0.0xmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexsi:schemaLocationhttp://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsdmodelVersion4.0.0/modelVersionparentgroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-parent/artifactIdversion4.0.0/versionrelativePath//parentgroupIdcom.example/groupIdartifactIdspring-ai-deepseek-demo/artifactIdversion0.0.1-SNAPSHOT/versionnamespring-ai-deepseek-demo/namepropertiesjava.version17/java.versionspring-ai.version2.0.0/spring-ai.version/propertiesdependencyManagementdependenciesdependencygroupIdorg.springframework.ai/groupIdartifactIdspring-ai-bom/artifactIdversion${spring-ai.version}/versiontypepom/typescopeimport/scope/dependency/dependencies/dependencyManagementdependencies!-- Web 接口 --dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-web/artifactId/dependency!-- Spring AI DeepSeek Chat 自动配置 --dependencygroupIdorg.springframework.ai/groupIdartifactIdspring-ai-starter-model-deepseek/artifactId/dependency!-- 测试依赖 --dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-test/artifactIdscopetest/scope/dependency/dependenciesbuildpluginsplugingroupIdorg.springframework.boot/groupIdartifactIdspring-boot-maven-plugin/artifactId/plugin/plugins/build/project版本说明Spring AI 2.0.x 对应 Spring Boot 4.0.x/4.1.x如果项目仍然使用 Spring Boot 3.x 请选择与之匹配的 Spring AI 1.x 版本不建议只修改 Spring Boot 或 Spring AI 的单个版本号最好按照 Spring AI 官方兼容矩阵整体调整。三、配置application.yml在src/main/resources/application.yml中添加以下内容server:port:8080spring:application:name:spring-ai-deepseek-demoai:deepseek:# 从环境变量中读取 API Key避免将密钥写入源码api-key:${DEEPSEEK_API_KEY}# DeepSeek OpenAI 兼容接口的基础地址base-url:https://api.deepseek.comchat:# 当前 API 文档推荐使用 deepseek-flash也可以根据账户能力选择其他模型model:deepseek-flash# 编程、数学类任务可以使用较低的 temperaturetemperature:0.7# 是否启用思考模式 按模型和 Spring AI 版本支持情况选择thinking:type:enabled在 Linux 或 macOS 中设置环境变量exportDEEPSEEK_API_KEY你的 DeepSeek API KeyWindows PowerShell$env:DEEPSEEK_API_KEY 你的 DeepSeek API Key关于模型名称不同时间点的 DeepSeek API 和 Spring AI 版本可能使用不同的模型名称。例如新版 DeepSeek API 文档中可见deepseek-flash、deepseek-v4-pro部分旧版示例使用deepseek-chat、deepseek-reasonerSpring AI 某些版本的默认值或示例可能出现deepseek-v4-flash、deepseek-v4-pro。如果启动后出现模型不存在、模型已下线等错误应以 DeepSeek 控制台和当前 API 文档中的可用模型列表为准并修改spring.ai.deepseek.chat.model。四、编写启动类packagecom.example.deepseek;importorg.springframework.boot.SpringApplication;importorg.springframework.boot.autoconfigure.SpringBootApplication;SpringBootApplicationpublicclassDeepSeekApplication{publicstaticvoidmain(String[]args){SpringApplication.run(DeepSeekApplication.class,args);}}添加spring-ai-starter-model-deepseek后Spring Boot 会自动创建 DeepSeek Chat 模型相关 Bean同时提供可注入的ChatClient.Builder。五、使用ChatClient调用 DeepSeek推荐使用 Spring AI 的ChatClient它提供了简洁的链式 API。packagecom.example.deepseek.controller;importorg.springframework.ai.chat.client.ChatClient;importorg.springframework.web.bind.annotation.GetMapping;importorg.springframework.web.bind.annotation.RequestParam;importorg.springframework.web.bind.annotation.RestController;RestControllerpublicclassChatController{privatefinalChatClientchatClient;publicChatController(ChatClient.BuilderchatClientBuilder){this.chatClientchatClientBuilder.build();}GetMapping(/ai/chat)publicStringchat(RequestParam(valuemessage,defaultValue请介绍一下 Spring AI)Stringmessage){returnchatClient.prompt().user(message).call().content();}}启动项目mvn spring-boot:run调用接口curl--gethttp://localhost:8080/ai/chat\--data-urlencodemessageSpring AI 的 ChatClient 有什么作用返回结果就是 DeepSeek 模型生成的文本 。六、设置系统提示词在实际项目中通常需要通过系统提示词约束模型的角色和输出风格。例如让模型始终以 Java 专家的身份回答问题packagecom.example.deepseek.config;importorg.springframework.ai.chat.client.ChatClient;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;ConfigurationpublicclassAiConfig{BeanpublicChatClientchatClient(ChatClient.Builderbuilder){returnbuilder.defaultSystem(你是一名资深 Java 专家请使用简洁、准确的中文回答问题。).build();}}此时控制器可以直接注入已经配置好的ChatClientpackagecom.example.deepseek.controller;importorg.springframework.ai.chat.client.ChatClient;importorg.springframework.web.bind.annotation.GetMapping;importorg.springframework.web.bind.annotation.RequestParam;importorg.springframework.web.bind.annotation.RestController;RestControllerpublicclassChatController{privatefinalChatClientchatClient;publicChatController(ChatClientchatClient){this.chatClientchatClient;}GetMapping(/ai/java-question)publicStringjavaQuestion(RequestParamStringquestion){returnchatClient.prompt().user(question).call().content();}}七、使用 Service 层封装调用逻辑如果项目规模较大建议不要把所有 AI 调用逻辑写在 Controller 中可以通过 Service 统一封装packagecom.example.deepseek.service;importorg.springframework.ai.chat.client.ChatClient;importorg.springframework.stereotype.Service;ServicepublicclassDeepSeekService{privatefinalChatClientchatClient;publicDeepSeekService(ChatClient.Builderbuilder){this.chatClientbuilder.defaultSystem(你是一个专业、严谨的中文智能助手。).build();}publicStringchat(Stringmessage){returnchatClient.prompt().user(message).call().content();}}Controllerpackagecom.example.deepseek.controller;importcom.example.deepseek.service.DeepSeekService;importorg.springframework.web.bind.annotation.GetMapping;importorg.springframework.web.bind.annotation.RequestParam;importorg.springframework.web.bind.annotation.RestController;RestControllerpublicclassDeepSeekController{privatefinalDeepSeekServicedeepSeekService;publicDeepSeekController(DeepSeekServicedeepSeekService){this.deepSeekServicedeepSeekService;}GetMapping(/ai/ask)publicStringask(RequestParamStringmessage){returndeepSeekService.chat(message);}}八、在运行时覆盖模型参数除了在application.yml中设置默认参数也可以针对某一次请求使用运行时选项覆盖模型和温度。不同 Spring AI 版本的选项构造器 API 可能略有变化下面给出常见写法importorg.springframework.ai.chat.client.ChatClient;importorg.springframework.ai.deepseek.DeepSeekChatOptions;publicStringcreativeChat(ChatClientchatClient,Stringmessage){returnchatClient.prompt().user(message).options(DeepSeekChatOptions.builder().model(deepseek-flash).temperature(1.2).build()).call().content();}如果编译器提示DeepSeekChatOptions的构造方法或方法名不匹配请以当前 Spring AI 版本的 JavaDoc 为准因为不同版本可能使用withModel、withTemperature或新的 builder 方法命名。九、异常处理建议生产环境不要把完整异常堆栈直接返回给前端可以统一处理异常并记录请求 IDpackagecom.example.deepseek.handler;importorg.springframework.http.HttpStatus;importorg.springframework.web.bind.annotation.ExceptionHandler;importorg.springframework.web.bind.annotation.ResponseStatus;importorg.springframework.web.bind.annotation.RestControllerAdvice;importjava.util.Map;RestControllerAdvicepublicclassGlobalExceptionHandler{ExceptionHandler(Exception.class)ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)publicMapString,StringhandleException(Exceptionex){// 实际项目中应使用日志框架记录 ex不建议将详细异常返回给客户端returnMap.of(message,AI 服务调用失败请稍后重试);}}对于网络抖动、临时服务不可用等问题可以结合 Spring AI 的spring.ai.retry配置调整重试策略spring:ai:retry:max-attempts:3backoff:initial-interval:1smultiplier:2max-interval:10s# 是否对客户端 4xx 错误进行重试通常保持 falseon-client-errors:false不要对无效 API Key、参数错误等 4xx 错误进行无限重试否则可能放大问题并增加调用成本。十、常见问题1. 启动时报 API Key 为空确认环境变量已经设置并且启动 Spring Boot 的终端能够读取到该变量echo$DEEPSEEK_API_KEY也可以临时在本地application.yml中配置但不要提交到公共仓库spring:ai:deepseek:api-key:sk-xxxxxxxx2. 返回 401 Unauthorized通常表示 API Key 无效、已撤销或请求使用了错误的账号密钥。重新检查 DeepSeek 控制台中的 Key并确认没有多余的空格和引号。3. 返回模型不存在检查spring.ai.deepseek.chat.model。模型名称会随着 DeepSeek API 版本调整优先使用账户当前可用的模型名。旧教程中的deepseek-chat不一定适用于当前账号或当前 API。4. 找不到ChatClient.Builder确认已添加spring-ai-starter-model-deepseekSpring AI BOM 与 starter 版本一致没有错误地使用旧版模块名项目确实启用了 Spring Boot 自动配置。5. 为什么不直接使用 WebClient 调用接口直接使用 WebClient 当然可以但需要自己处理请求结构、响应解析、重试、模型选项和消息抽象。Spring AI 的价值在于提供统一的 Chat Model 和ChatClient抽象后续切换其他模型时业务代码改动更小。十一、项目目录示例spring-ai-deepseek-demo ├── pom.xml └── src └── main ├── java │ └── com/example/deepseek │ ├── DeepSeekApplication.java │ ├── config │ │ └── AiConfig.java │ ├── controller │ │ └── ChatController.java │ └── service │ └── DeepSeekService.java └── resources └── application.yml十二、总结使用 Spring AI 接入 DeepSeek 的核心步骤只有三步在pom.xml中引入spring-ai-starter-model-deepseek在application.yml中配置spring.ai.deepseek.api-key和模型名称注入ChatClient.Builder通过prompt().user(...).call().content()发起调用。完整调用代码非常简洁returnchatClient.prompt().user(message).call().content();在生产环境中还应进一步完善 API Key 管理、超时控制、重试策略、日志脱敏、调用限流、Token 成本统计以及敏感内容审核等机制。参考资料Spring AI DeepSeek Chat 官方文档Spring AI Getting StartedSpring AI ChatClient 官方文档DeepSeek API 官方文档DeepSeek API Keys
RELATED

相关推荐

SPFA 算法简介及经典实例

SPFA 算法简介及经典实例

● SPFA 算法 (1)SPFA 算法,即最短路径快速算法,是基于 Bellman-Ford 算法优化而来的单源最短路径算法,适用于带负权边、无负权环的有向图或无向图,在算法竞赛中应用广泛。 (2)SPFA …

📅 2026/11/17 16:42:25
GCC 参数记不住?这份语法速查 + 多参数组合示例,收藏就够

GCC 参数记不住?这份语法速查 + 多参数组合示例,收藏就够

代码写得没问题,一编译却蹦出一堆 undefined reference to xxx。改了半天,最后发现是命令里库的顺序写反了。今天把 GCC 语法、核心参数、多参数组合,以及最容易踩的链接顺序坑,一篇讲清。 一、gcc 基本语法 一条 gcc 命令长这样…

📅 2026/11/1 11:23:14
Kubernetes 1.30 从零安装实战:架构、二进制与 kubeadm 全解析

Kubernetes 1.30 从零安装实战:架构、二进制与 kubeadm 全解析

一、前置规划(集群设计) 1.网络规划 根据自己资源合理规划 2. 网络规划 集群 Pod 网段:10.244.0.0/16(Flannel/Calico 默认网段) 集群 Service 网段:10.96.0.0/12(K8s 默认 Service 网段&a…

📅 2026/11/1 9:58:36
MORE NEWS

更多资讯

📰

大自然电工证考试复审延期怎么办理

你在外省考的电工证能不能转过来?真实经历告诉你怎么操作 之前考的证在外省能不能转过来?我去年刚从河南信阳浉河区调岗到外地,就遇到这个问题。其实很多人都在问,尤其是在跨省工作、换城市生活的情况下,如何把之前考的电工证顺利转过来。今天我就结合自…

📰

工地太忙根本没时间复习考试?新郑高压电工证报名在哪考全攻略

工地太忙根本没时间复习考试?新郑高压电工证报名在哪考全攻略 工地太忙根本没时间复习考试?新郑高压电工证报名在哪考成了很多电工师傅的头等大事。特别是对于在济源从事水利工程的你来说,高压电工证不仅是上岗的“通行证”,更是安全作业的“护身符”。但…

📰

电工证免培训考试时间报考条件与考试时间

安阳在职建筑工人考电工证怕挂科?掌握免培训考试时间+上岗必备技巧 实操考试心里没底怕挂科,特别是像我们安阳的建筑工人,很多都是半路出家,想转行或者提升技能,第一步就是拿下电工证。但一想到考试,心里就打鼓,怕操作不规范、流程不熟悉,万一挂了,…

📰

西安考电工证学校通过率揭秘:急需特种作业证才能上岗找工作?

西安考电工证学校通过率揭秘:急需特种作业证才能上岗找工作? 你有没有过这种经历?手上拿着简历,投了十几份工作,却因为没有 特种作业操作证 而被拒之门外?别急,这不是你一个人的烦恼,而是整个行业的硬性门槛。特别是在像 西安考电工证学校…

📰

红安住建部电工证多少钱 为啥工地电工证考前必须知道这些?

红安住建部电工证多少钱 为啥工地电工证考前必须知道这些? 工地太忙根本没时间复习考试,红安住建部电工证多少钱?这个问题几乎成了每个施工一线人员最头疼的事。尤其是那些需要持证上岗的岗位,像低压电工、高压电工、焊工、登高作业等,要是证书没过期、…

📰

电工证安装教程在哪考?怕考不过白交培训费别慌

电工证安装教程在哪考?怕考不过白交培训费别慌 你怕电工证考不过,培训费打水漂?别急,今天就告诉你【电工证安装教程在哪考】,从洛阳市政公用工程从业者的角度,手把手教你避开那些坑,稳稳拿到证。 案例背景:洛阳市政项目现场的电工证危机…

TODAY

今日更新

THIS WEEK

本周精选

THIS MONTH

本月热门

读完文章,想聊聊您的网站?

告诉我们您的行业与需求,资深顾问一对一梳理方案与报价,全程免费。

📞 💬