跳到主要内容
Spring AI 核心功能与实战入门 | 极客日志
Java AI java 算法
Spring AI 核心功能与实战入门 Spring AI 框架将 AI 大模型能力集成到 Java 生态中,支持聊天、图像生成及函数调用等功能。本文涵盖 DeepSeek、Ollama 及阿里云百炼的接入方式,详解 ChatClient 与 ChatModel 的使用差异,流式响应实现,以及 RAG(检索增强生成)在知识库问答中的应用。通过综合案例展示如何构建智能招聘助手,帮助开发者快速上手 Spring AI 开发。
山野诗人 发布于 2026/3/24 更新于 2026/6/8 24 浏览Spring AI 简介
在人工智能飞速发展的今天,AI 已成为各行各业的基础设施。作为主流的 Java 应用开发框架,Spring 社区紧跟趋势推出了 Spring AI 框架,旨在将 Spring 生态的设计原则(如可移植性、模块化)应用到 AI 领域。
什么是 Spring AI
Spring AI 是一个 AI 工程领域的应用程序框架。它的核心目标是提供开发 AI 大模型应用所需的基本抽象模型,拥有多种实现方式,使得开发者可以用很少的代码改动就能实现组件的轻松替换。简言之,它提供了一个友好的 API 和开发 AI 应用的抽象,简化了 AI 大模型应用的开发工作。
目前版本分为预览版 (PRE)、快照版 (SNAPSHOT) 以及正式版 (GA)。推荐使用 GA 版本以保证稳定性。
主要功能
支持主流 AI 大模型供应商:OpenAI、DeepSeek、Microsoft、Ollama、Amazon、Google HuggingFace 等。
支持 AI 大模型类型:聊天、文本到图像、文本到声音等。
支持主流的 Embedding Models 和向量数据库:Azure Vector Search、Chroma、Milvus、Neo4j、Redis、PineCone、PostgreSQL/PGVector 等。
把 AI 大模型输出映射到简单的 Java 对象(POJOs)上。
支持函数调用 (Function Calling) 功能。
为数据工程提供 ETL 框架。
支持 Spring Boot 自动配置和快速启动。
快速入门
准备工作
我们以 DeepSeek 为例进行集成。DeepSeek 是一款由深度求索开发的 AI 大模型,基于 Transformer 架构,在成本、性能及多模态处理方面表现优异。
获取 API Key :访问 DeepSeek 开放平台注册账号并创建 API Key。
环境要求 :建议使用 JDK 17+ 和 Spring Boot 3.x。
创建 SpringBoot 工程
创建一个 SpringBoot 项目,并在 pom.xml 中添加公共依赖:
<properties >
<maven.compiler.source > 17</maven.compiler.source >
<maven.compiler.target > 17</maven.compiler.target >
<spring-ai.version > 1.0.0-M5</spring-ai.version >
</properties >
<dependencies >
<dependency >
<groupId > org.springframework.boot</groupId >
< > spring-boot-starter-web
org.springframework.ai
spring-ai-openai-spring-boot-starter
org.springframework.boot
spring-boot-starter-test
test
org.projectlombok
lombok
1.18.30
org.springframework.ai
spring-ai-bom
${spring-ai.version}
pom
import
artifactId
</artifactId >
</dependency >
<dependency >
<groupId >
</groupId >
<artifactId >
</artifactId >
</dependency >
<dependency >
<groupId >
</groupId >
<artifactId >
</artifactId >
<scope >
</scope >
</dependency >
<dependency >
<groupId >
</groupId >
<artifactId >
</artifactId >
<version >
</version >
</dependency >
</dependencies >
<dependencyManagement >
<dependencies >
<dependency >
<groupId >
</groupId >
<artifactId >
</artifactId >
<version >
</version >
<type >
</type >
<scope >
</scope >
</dependency >
</dependencies >
</dependencyManagement >
配置文件 在 application.properties 中配置 API Key 和基础信息:
server.port=8899
spring.application.name=spring-ai-deepseek-demo
# DeepSeek 的 Api key
spring.ai.openai.api-key=sk-****************
spring.ai.openai.base-url=https://api.deepseek.com
spring.ai.openai.chat.options.model=deepseek-chat
spring.ai.openai.chat.options.temperature=0.7
其中 temperature 参数用于控制生成文本的多样性。值越高越多样化,值越低越接近确定性结果。
编写代码 @SpringBootApplication
public class SpringAiHelloApplication {
public static void main (String[] args) {
SpringApplication.run(SpringAiHelloApplication.class, args);
}
}
package com.example.ai.controller;
import jakarta.annotation.Resource;
import org.springframework.ai.openai.OpenAiChatModel;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ChatDeepSeekController {
@Resource
private OpenAiChatModel chatModel;
@GetMapping("/ai/generate")
public String generate (@RequestParam(value = "message", defaultValue = "hello") String message) {
String response = this .chatModel.call(message);
System.out.println("response: " + response);
return response;
}
}
接口测试时输入 localhost:8899/ai/generate?message=你好,即可看到模型响应。
聊天模型详解
ChatClient 接口 ChatClient 是定义与聊天服务交互客户端的接口,主要用于创建聊天客户端对象、设置请求规范及发起请求。
简单对话 通过 ChatClient.Builder 注入客户端,使用链式调用构建提示词:
package com.example.ai.controller;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ChatController {
private final ChatClient chatClient;
public ChatController (ChatClient.Builder chatClientBuilder) {
this .chatClient = chatClientBuilder.build();
}
@GetMapping("/chat")
public String chat (@RequestParam(value = "message", defaultValue = "你是谁") String message) {
return this .chatClient.prompt()
.user(message)
.call()
.content();
}
}
角色预设 可以通过配置 Bean 设置默认的系统提示词(System Prompt),让 AI 扮演特定角色:
package com.example.ai.config;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AIConfig {
@Bean
public ChatClient chatClient (ChatClient.Builder builder) {
return builder.defaultSystem("你是一名 Java 开发专家,精通技术细节,名字叫助手。" ).build();
}
}
流式响应 非流式输出 (call) 等待全部生成后返回,而流式输出 (stream) 逐个字符输出,能显著提升用户体验,特别是在推理效率不高时。
@GetMapping(value = "/chat/stream", produces = "text/html;charset=UTF-8")
public Flux<String> chatStream (@RequestParam(value = "message") String message) {
return chatClient.prompt().user(message).stream().content();
}
ChatModel 接口 ChatModel 定义了与 AI 模型交互的基本方法。虽然 ChatClient 底层使用了 ChatModel,但在需要更精细控制 Prompt 或 Options 时,直接使用 ChatModel 更为灵活。
@GetMapping("/chatModel02")
public String chatModel02 (@RequestParam("message") String message) {
ChatResponse call = chatModel.call(new Prompt (
message,
OpenAiChatOptions.builder()
.model("deepseek-chat" )
.temperature(0.8 )
.build()
));
return call.getResult().getOutput().getContent();
}
提示词管理 Prompt 模板允许我们在运行时动态替换关键词。例如,可以定义一个包含 {name} 和 {voice} 占位符的模板,并在调用时传入具体值。
函数调用 Spring AI 的函数调用功能允许大语言模型在生成回答时触发预定义的外部函数,从而实现动态数据获取或业务逻辑操作。
实现流程
定义函数 :声明可供模型调用的函数(名称、描述、参数结构)。
模型交互 :将函数信息与用户输入一起发送给模型。
执行函数 :解析模型的调用请求,执行业务逻辑。
返回结果 :将执行结果返回给模型生成最终回答。
代码示例 package com.example.config;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Description;
import java.util.function.Function;
@Slf4j
@Configuration
public class CalculatorService {
public record AddOperation (int a, int b) {}
public record MulOperation (int m, int n) {}
@Bean
@Description("加法运算")
public Function<AddOperation, Integer> addOperation () {
return request -> {
log.info("执行加法运算:{} + {} = {}" , request.a, request.b, request.a + request.b);
return request.a + request.b;
};
}
@Bean
@Description("乘法运算")
public Function<MulOperation, Integer> mulOperation () {
return request -> {
log.info("执行乘法运算:{} * {} = {}" , request.m, request.n, request.m * request.n);
return request.m * request.n;
};
}
}
@GetMapping(value = "/function", produces = MediaType.APPLICATION_STREAM_JSON_VALUE)
public String ragJsonText (@RequestParam(value = "message") String message) {
return ChatClient.builder(chatModel).build()
.prompt()
.system("您是算术计算器的代理。当用户询问数学计算时,必须调用相应的函数来处理。" )
.user(message)
.functions("addOperation" , "mulOperation" )
.call()
.content();
}
本地部署 Ollama Ollama 是一个用于本地化部署和管理大型语言模型的工具,方便开发者在自己的电脑上运行开源模型。
安装与配置
下载并安装 Ollama。
设置环境变量 OLLAMA_MODELS 指定模型存储路径。
拉取模型,例如:ollama pull deepseek-r1:1.5b。
启动服务,默认监听 http://localhost:11434。
Spring AI 集成 添加 spring-ai-ollama-spring-boot-starter 依赖,并在配置文件中指定 Base URL:
spring.ai.ollama.base-url=http://localhost:11434
spring.ai.ollama.chat.options.model=deepseek-r1:1.5b
Spring AI Alibaba Spring AI Alibaba 是阿里云通义系列模型及服务在 Java AI 应用开发领域的最佳实践,提供了完整的开源配套。
快速接入
申请阿里云 API Key。
引入 spring-ai-alibaba-starter 依赖。
配置 application.properties,注意排除默认的 OpenAI 自动配置以避免冲突。
this .dashScopeChatClient = chatClientBuilder
.defaultSystem(DEFAULT_PROMPT)
.defaultAdvisors(new MessageChatMemoryAdvisor (new InMemoryChatMemory ()))
.defaultOptions(DashScopeChatOptions.builder().withTopP(0.7 ).build())
.build();
其他模型能力
图像模型 Spring AI 的 Image Model API 提供了文生图的能力。通过 ImageModel 接口,可以调用不同的图像生成模型。
@GetMapping("/generate-image")
public void getImage (@RequestParam(value = "msg", defaultValue = "生成一只小猫") String msg, HttpServletResponse res) {
ImageResponse response = imageModel.call(new ImagePrompt (
msg,
DashScopeImageOptions.builder()
.withModel(DashScopeImageApi.DEFAULT_IMAGE_MODEL)
.withN(1 )
.withHeight(1024 )
.withWidth(1024 )
.build()
));
}
语音模型 Text-to-Speech API 支持将文字内容转化为语音音频,可配置语速、音调等参数。
RAG 检索增强生成 RAG (Retrieval-Augmented Generation) 结合了检索系统和生成模型,利用外部知识库帮助大模型生成更加准确、有依据的回答,有效解决知识局限性和幻觉问题。
基本流程
向量化 :将文档转换为高维向量。
检索 :根据用户问题向量在向量数据库中检索相似片段。
构建上下文 :将检索到的片段与系统提示词结合。
生成回答 :LLM 基于上下文生成最终答案。
实现步骤
初始化 SimpleVectorStore 并加载文档。
在 ChatClient 中添加 QuestionAnswerAdvisor,关联向量存储。
@Bean
VectorStore vectorStore (@Qualifier("dashscopeEmbeddingModel") EmbeddingModel embeddingModel) {
SimpleVectorStore simpleVectorStore = SimpleVectorStore.builder(embeddingModel).build();
List<Document> documents = List.of(new Document ("产品说明:Java 是一种面向对象开发语言..." ));
simpleVectorStore.add(documents);
return simpleVectorStore;
}
综合案例:智能简历筛选 结合 RAG 和函数调用,我们可以构建一个智能招聘助手。
搭建环境 :创建子模块,配置端口。
创建知识库 :将候选人简历文本放入资源目录,通过 TextReader 读取并切分,存入向量库。
创建工具 :定义查询岗位匹配度的函数。
编写人设 :设定系统提示词,明确助手角色、指导原则及限制。
串联应用 :在 Controller 中检索知识库,构造 Prompt,并启用函数调用。
@GetMapping("/ai/agent")
public String agent (@RequestParam("query") String query) {
List<Document> documents = vectorStore.similaritySearch(query);
String info = documents.size() > 0 ? documents.get(0 ).getContent() : "" ;
String systemPrompt = "你是一个招聘助手..." ;
String userPrompt = "给你提供一些数据参考:{info},请回答我的问题:{query}。" ;
}
通过这种方式,开发者可以快速构建具备专业领域知识的 AI 应用。
相关免费在线工具 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
加密/解密文本 使用加密算法(如AES、TripleDES、Rabbit或RC4)加密和解密文本明文。 在线工具,加密/解密文本在线工具,online
RSA密钥对生成器 生成新的随机RSA私钥和公钥pem证书。 在线工具,RSA密钥对生成器在线工具,online