Spring AI 实战:用 Java 搞 AI,从此告别调参侠

大家好!我是你们的 Java 老司机,今天咱们不聊 MyBatisSpring 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 关键依赖:

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:

yaml 复制代码
spring:
  ai:
    deepseek:
      api-key: "你的-DeepSeek-API-KEY"  # 去官网申请
      chat:
        model: deepseek-chat  # 默认模型
        temperature: 0.7      # 创意度 (0=保守, 1=放飞自我)

4. 写个 AI 聊天接口(自动怼产品经理)

直接上代码!

(1) 创建 ChatController

java 复制代码
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);
    }
}

测试效果:

bash 复制代码
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(适合长时间任务):

java 复制代码
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 全套代码!

java 复制代码
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());
}

测试:

bash 复制代码
curl "http://localhost:8080/ai/gen-crud?tableName=User"

输出示例:

java 复制代码
@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 生态整合(安全、事务、缓存一键接入)
相关推荐
腻害兔7 小时前
【若依项目-产品经理视角】深度拆解 RuoYi-Vue-Pro 商城模块:从商品管理到交易引擎,50 张表撑起一整套电商系统
java·大数据·vue.js·产品经理·ai编程
GetcharZp8 小时前
抛弃低效SSH!这套Ansible+Web可视化神器,让你天天准点下班!
后端
码智社8 小时前
AES加密原理详解及Java实现加解密实战
java·开发语言
萧瑟余晖9 小时前
JDK 26 新特性详解
java·开发语言
马优晨9 小时前
Freemarker 完整讲解(后端 Java 模板引擎)
java·开发语言·freemarker·freemarker 完整讲解·freemarker模板引擎
weixin_4462608511 小时前
HACO:面向动态部署环境的对冲式智能计算可靠多智能体调度框架
后端·python·flask
ttwuai12 小时前
Cursor 生成 CRUD 后,Go 后台接口别只测 200:JWT、RBAC 和 tenant_id 怎么验
开发语言·后端·golang
用户83562907805112 小时前
Python 实现 Excel 页面布局与打印设置自动化
后端·python
维天说12 小时前
CLI-Switch 2026年3月版历史设计:Hook、TTY 隔离与 JSON 状态
java·服务器·json