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

大家好!我是你们的 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 关键依赖:

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 生态整合(安全、事务、缓存一键接入)
相关推荐
自强的小白几秒前
MYbatis-plus(自定义sql)
java·sql·mybatis
古法安卓1 分钟前
Android-Ext4文件系统问题排查
android·java·android studio
Escalating_xu4 分钟前
【C 语言】深入理解指针(3):字符指针、数组指针、二维数组传参、函数指针与转移表
java·c语言·开发语言
对象存储与RustFS18 分钟前
自建对象存储的第一个决定:单机就够,还是必须上分布式
后端·rust·开源
不正经的码狗21 分钟前
Java 开发环境搭建与 Eclipse 使用速通教程
java·开发语言·eclipse
用户81818706274621 分钟前
第37章 Java应用在K8s里的经典坑:容器内存/CPU limit与JVM参数不匹配导致的OOMKilled
java·后端
小小张说故事28 分钟前
pandas 读大 CSV 太慢?6 个实测提速技巧(dtype / 分块 / 引擎选择)
后端·python·pandas
马剑威(威哥爱编程)35 分钟前
【AI全栈后端12-03】Spring Boot 用多模型路由把智能客服成本降下来
java·人工智能·spring boot
喵个咪36 分钟前
GoWind Admin|风行 — 开箱即用的企业级全栈中后台框架:多租户与行级数据隔离
后端·go
霸道流氓气质39 分钟前
AI模型幻觉检测与抑制完全指南:从规则引擎到RAG对比的Java生产级实战
java·开发语言·人工智能