大家好!我是你们的 Java 老司机,今天咱们不聊 MyBatis
和 Spring Cloud
,来点更刺激的——用 Spring AI 开发 AI 应用!
以前搞 AI 得学 Python、调 TensorFlow、被 PyTorch 折磨……现在好了,Spring AI 来了,Java 程序员也能愉快玩 AI 了! 🎉
今天,我们就用 Spring AI + DeepSeek,手把手教你搞个能自动写代码、智能问答、甚至帮你怼产品经理的 AI 应用!
1. Spring AI 是啥?能吃吗?
Spring AI 是 Spring 官方推出的 AI 集成框架,让你能用熟悉的 Spring 风格调用各种 AI 能力,比如:
- 聊天模型(ChatGPT、DeepSeek、Claude...)文生图模型(Stable Diffusion、DALL·E...)Embedding 模型(做语义搜索、推荐系统)甚至自定义 AI 模型(如果你够硬核)
优点:
✅ 不用学 Python,Java 一把梭!
✅ 统一 API,换 AI 模型只需改配置
✅ Spring 生态整合(事务、缓存、安全一把梭)
2. 先搞个 SpringBoot 项目
用 Spring Initializr(或 IDEA 直接生成),选:
- Spring Boot 3.2+Spring AI(目前是 0.8 版本)
pom.xml 关键依赖:
<dependencies> <!-- SpringBoot Web --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- Spring AI (核心) --> <dependency> <groupId>org.springframework.ai</groupId> <artifactId>spring-ai-core</artifactId> <version>0.8.0</version> <!-- 以最新版为准 --> </dependency> <!-- DeepSeek 支持(Spring AI 的 DeepSeek 模块) --> <dependency> <groupId>org.springframework.ai</groupId> <artifactId>spring-ai-deepseek</artifactId> <version>0.8.0</version> </dependency></dependencies>
3. 配置 DeepSeek API(让 AI 干活)
在 application.yml
里配置 DeepSeek:
spring: ai: deepseek: api-key: "你的-DeepSeek-API-KEY" # 去官网申请 chat: model: deepseek-chat # 默认模型 temperature: 0.7 # 创意度 (0=保守, 1=放飞自我)
4. 写个 AI 聊天接口(自动怼产品经理)
直接上代码!
(1) 创建 ChatController
import org.springframework.ai.chat.ChatClient;import org.springframework.web.bind.annotation.*;@RestController@RequestMapping("/ai")public class ChatController { private final ChatClient chatClient; // Spring AI 自动注入 public ChatController(ChatClient chatClient) { this.chatClient = chatClient; } @GetMapping("/chat") public String chat(@RequestParam String message) { return chatClient.call(message); // 一句话调用 AI! } // 高级玩法:让 AI 自动拒绝产品需求 @GetMapping("/reject") public String rejectRequirement() { String prompt = """ 产品经理说:“这个需求很简单,明天能上线吗?” 你作为资深程序员,请用专业但委婉的方式拒绝, 要求:带点幽默感,不超过 50 字 """; return chatClient.call(prompt); }}
测试效果:
curl "http://localhost:8080/ai/chat?message=用Java写个快速排序"# 输出:public class QuickSort { public static void sort(int[] arr) { ... }}curl "http://localhost:8080/ai/reject"# 输出:这个需求的时间复杂度是 O(梦想),目前服务器算力不支持~
(2) 流式响应(像 ChatGPT 一样逐字输出)
Spring AI 还支持 流式 API(适合长时间任务):
import org.springframework.ai.chat.StreamingChatClient;import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;@GetMapping("/stream")public SseEmitter streamChat(@RequestParam String message) { SseEmitter emitter = new SseEmitter(); streamingChatClient.stream(message) .subscribe( chunk -> emitter.send(chunk.getContent()), // 每块数据实时发送 error -> emitter.completeWithError(error), // 出错处理 emitter::complete // 完成 ); return emitter;}
5. 高级玩法:让 AI 自动写 CRUD 代码
场景:输入表名,自动生成 Controller -> Service -> Repository
全套代码!
import org.springframework.ai.prompt.PromptTemplate;@GetMapping("/gen-crud")public String generateCrud(@RequestParam String tableName) { PromptTemplate prompt = new PromptTemplate(""" 请用 SpringBoot 生成 {table} 表的完整 CRUD 代码,要求: 1. 使用 @RestController 2. 使用 JPA 实现 3. 包含 Swagger 注解 返回格式:Java 代码块 """); prompt.add("table", tableName); return chatClient.call(prompt.render());}
测试:
curl "http://localhost:8080/ai/gen-crud?tableName=User"
输出示例:
@RestController@RequestMapping("/api/users")@Tag(name = "用户管理")public class UserController { @Autowired private UserRepository userRepo; @GetMapping @Operation(summary = "查询所有用户") public List<User> getAll() { return userRepo.findAll(); } // 其他 CRUD 方法...}
6. 可能遇到的坑
🚨 API Key 无效 → 检查是否拼错,或去 DeepSeek 官网确认
🚨 依赖冲突 → 确保 Spring Boot 和 Spring AI 版本兼容
🚨 AI 胡说八道 → 调整 temperature
参数(调低更保守)
7. 总结
今天我们用 Spring AI + DeepSeek 实现了:
✅ 智能聊天(/ai/chat
)
✅ 自动拒绝需求(/ai/reject
,打工人必备)
✅ 代码生成(/ai/gen-crud
,告别手写样板代码)
Spring AI 的优势:
- Java 原生支持,不用切 Python统一接口,轻松切换 AI 供应商Spring 生态整合(安全、事务、缓存一键接入)