跳到主要内容
极客日志极客日志面向AI+效率的开发者社区
首页博客GitHub 精选镜像工具UI配色美学隐私政策关于联系
搜索内容 / 工具 / 仓库 / 镜像...⌘K搜索
注册
博客列表
JavaAIjava

Spring AI:Java 生态原生 AI 框架入门指南

综述由AI生成Spring AI 是面向 Java 生态的原生 AI 框架,提供统一接口适配多供应商模型。介绍其核心特性,包括标准化 API、Spring Boot 集成、RAG 支持及工具调用。通过 Deepseek 案例演示了环境搭建、依赖配置、代码编写及流式响应可视化界面的实现,帮助开发者快速接入 AI 能力。

RustyLab发布于 2026/4/5更新于 2026/5/2330 浏览
Spring AI:Java 生态原生 AI 框架入门指南

Spring AI:Java 生态原生 AI 框架入门指南

在大模型席卷全球的技术浪潮下,Java 开发者们迫切需要一款贴合自身生态、低门槛接入 AI 能力的框架。Spring AI 的出现,恰好填补了这一空白 —— 它并非简单移植 Python 生态的现有方案,而是深度遵循 Spring 设计哲学,为 Java 和 Spring 开发者打造了原生的 AI 开发框架。本文将从 Spring AI 的核心概念、核心特性出发,结合实际环境搭建与首个对话案例,带大家快速上手这款框架,解锁 Java 生态与 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)等高级场景的核心需求。

官方文档 官网地址:https://spring.io/projects/spring-ai 官方文档:https://docs.spring.io/spring-ai/reference/index.html 中文文档:https://spring-ai.spring-doc.cn/docs/1.0.0/index.html

二、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,保障类型安全,避免繁琐的字符串解析与类型转换,降低维护成本。

目录

  1. Spring AI:Java 生态原生 AI 框架入门指南
  2. 一、什么是 Spring AI?
  3. 二、Spring AI 核心特性:为什么值得选?
  4. 1. 全栈多供应商模型适配,覆盖主流 AI 能力
  5. 2. 标准化抽象 API,统一调用体验
  6. 3. 原生集成 Spring Boot,开箱即用
  7. 4. 结构化输出与类型安全,降低维护成本
  8. 5. 内置向量存储与 RAG 支持,激活私有知识库
  9. 6. 工具调用能力,打通业务系统闭环
  10. 三、快速上手:环境准备与 Deepseek 对话案例
  11. 3.1 环境要求
  12. 3.2 创建 Spring Boot 项目
  13. Deepseek URL
  14. 四、实战进阶:流式响应与可视化界面优化
  15. Step 1:实现流式返回接口
  16. Step 2:创建可视化聊天界面
  17. Step 3:启动并测试
  18. 总结
  • 💰 8折买阿里云服务器限时8折了解详情

5. 内置向量存储与 RAG 支持,激活私有知识库

Spring AI 集成了 PostgreSQL/pgvector、Pinecone、Qdrant、Redis、Weaviate 等主流向量数据库,提供元数据过滤、相似度检索能力;同时内置 ETL 流程,可快速搭建 RAG 系统,解决大模型'知识过期''不懂私有数据'痛点。

6. 工具调用能力,打通业务系统闭环

原生支持模型驱动的工具调用,可将 Spring Bean 注册为 AI 可调用工具,实现 AI 自动调用业务接口、查询数据库等操作,例如:

  • 调用天气 API 获取实时气象数据
  • 查询企业 CRM 系统获取客户详情
  • 执行业务数据统计与分析操作

实现 AI 与业务流程深度融合,让 AI 从'对话工具'升级为'业务智能入口',打通需求到执行的全闭环。

三、快速上手:环境准备与 Deepseek 对话案例

理论再多不如实际动手,下面我们将通过一个完整的案例,教大家搭建 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 项目

Step 1:访问 Spring Initializr 访问 https://start.spring.io/,或在 IDEA 中直接创建 New Module。项目配置如下:

  • Name: spring-ai-demo
  • Group: com.example
  • Artifact: spring-ai-demo
  • Package name: com.example.demo
  • Language: Java
  • JDK: 17
  • Spring Boot: 3.5.3
  • Packaging: Jar

Step 2:添加依赖 Spring Boot 版本选择 3.5.x,依赖选择:仅需添加「Spring Web」依赖(后续通过 Maven 引入 Spring AI 相关依赖)。

创建完成后的项目结构如下:

spring-ai-demo/
├── src/
│   ├── main/
│   │   ├── java/
│   │   │   └── com/
│   │   │       └── example/
│   │   │           └── demo/
│   │   │               └── DemoApplication.java
│   │   └── resources/
│   │       └── application.properties
│   └── test/
└── pom.xml

Step 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>spring-ai-parent</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <artifactId>spring-ai-demo</artifactId>
    <name>spring-ai-demo</name>
    <description>Spring AI Quick Start</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>

Step 4:配置 application.properties 在 src/main/resources/application.properties 中配置 Deepseek 模型的基础信息:

spring.application.name=spring-ai-demo
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 官网注册获取,替换配置中的占位符。

Step 5:编写 ChatController 创建 com.example.demo.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) {
        return chatModel.call(message);
    }
}

Step 6:启动并测试 运行 DemoApplication.java 启动项目。 浏览器访问:http://localhost:8080/ai/chat?message=你是谁,即可看到模型响应。

四、实战进阶:流式响应与可视化界面优化

前面使用 Spring AI 快速整合 DeepSeek,实现了与大模型对话的功能,但是,这个项目存在两个不足:

  1. 无可视化交互界面;
  2. AI 响应为一次性返回,缺乏实时感。 下面对项目进行优化升级。

Step 1:实现流式返回接口

在 ChatController 中,创建新接口 /ai/chatStream 接口。

@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, 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-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) {
        addMessage(message, true);
        sendButton.disabled = true;
        try {
            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 = ;
             () {
                 { done, value } =  reader.();
                 (done) ;
                 chunk = decoder.(value, { :  });
                 lines = chunk.().( line.());
                 ( line  lines) {
                     {
                         cleanLine = line.(, ).();
                         (!cleanLine) ;
                         data = .(cleanLine);
                         (data.) { fullText += data.; }
                    }  (e) { .(, e); }
                }
                (fullText, );
            }
        }  (error) {
            ( + error., );
        }  {
            sendButton. = ;
            messageInput.();
        }
    }

     () {
         messageDiv = .();
        messageDiv. = ;
         messageContent = .();
        messageContent. = ;
        messageContent. = content;
        messageDiv.(messageContent);
        chatMessages.(messageDiv);
        chatMessages. = chatMessages.;
    }

    chatForm.(,  (e) => {
        e.();
         message = messageInput..();
         (!message) ;
        messageInput. = ;
         (message);
    });
</script>
</body>
</html>

Step 3:启动并测试

重启项目后,访问 http://localhost:8080,即可通过可视化界面与 AI 聊天,例如输入'你好',模型会流式返回。

在这里插入图片描述

总结

本文我们从 Spring AI 的核心概念出发,详细介绍了它的核心特性,并通过一个完整的 Deepseek 对话案例,带大家完成了环境搭建、依赖配置、代码编写与测试的全流程。Spring AI 的核心优势在于'原生集成 Spring 生态'与'统一抽象接口',让 Java 开发者无需跨生态就能快速接入 AI 能力,极大降低了 AI 应用的开发门槛。

''
while
true
const
await
read
if
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 失败:'
addMessage
false
catch
addMessage
'抱歉,发生了错误:'
message
false
finally
disabled
false
focus
function
addMessage
content, isUser
const
document
createElement
'div'
className
`message ${isUser ? 'user' : 'assistant'}`
const
document
createElement
'div'
className
'message-content'
textContent
appendChild
appendChild
scrollTop
scrollHeight
addEventListener
'submit'
async
preventDefault
const
value
trim
if
return
value
''
await
sendMessage
  • Magick API 一键接入全球大模型注册送1000万token查看
  • 🤖 一键搭建Deepseek满血版了解详情
  • 一键打造专属AI 智能体了解详情
极客日志微信公众号二维码

微信扫一扫,关注极客日志

微信公众号「极客日志V2」,在微信中扫描左侧二维码关注。展示文案:极客日志V2 zeeklog

更多推荐文章

查看全部
  • 2025 年秋招 LLM 及多模态模型面试精华
  • 基于 Java Swing 的个人所得税计算模拟器实现
  • 基于 Whisper 的多语种交互异常检测框架实战
  • 前端开发基础:HTML/CSS/JavaScript 核心与开发环境入门
  • 前端开发者 Agent 工程化开发学习路线
  • Browser-Use 本地部署及远程访问自动化方案
  • PyCharm 调用 AI 模型 API 辅助编程指南
  • 手机端运行 Stable Diffusion 的开源 AI 绘画工具
  • Ubuntu 24.04 国内镜像源替换方法
  • 插件式架构实战:基于 C++ 与 C# 的软件解耦方案
  • Java 8 新日期时间 API 核心用法详解
  • Flutter 底部导航与 TabBar 多页切换实战及鸿蒙适配
  • 开源 GEO 优化工具源码部署搭建指南
  • 本地搭建带知识库的 AI 助手:Ollama + Open WebUI 实战指南
  • C++ 笔试算法实战:打怪、字符串分类与城市群计数
  • CVE-2026-21962 Oracle WebLogic 代理插件未授权 RCE 检测与利用
  • Python 数据可视化基础与应用
  • LightRAG 本地部署与 WebUI 应用实战
  • 基于FPGA的积分梳状CIC滤波器Verilog设计探秘
  • FPGA 比特流 (Bitstream) 深度解析

相关免费在线工具

  • 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