SpringAI
Spring AI 是 Spring 官方针对人工智能(AI)应用开发推出的标准化框架。
它的核心宗旨是将 Spring 开发者熟悉的“依赖注入、统一抽象、声明式配置、面向接口编程”等生态优势,完美复刻到 AI 和大模型开发领域。
Java 程序员,想在项目里接入大模型、搞 RAG 知识库或者搞 Agent,Spring AI 就是量身定制的大模型开发脚手架。
Spring AI 如何调用模型
Spring AI 推荐使用ChatClient;Spring Boot 会根据 starter 和配置自动创建ChatModel、EmbeddingModel与ChatClient.Builder。
Spring AI ChatClient 文档
1. Maven 依赖
使用 Ollama:
<dependencyManagement><dependencies><dependency><groupId>org.springframework.ai</groupId><artifactId>spring-ai-bom</artifactId><version>2.0.0</version><type>pom</type><scope>import</scope></dependency></dependencies></dependencyManagement><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.ai</groupId><artifactId>spring-ai-starter-model-ollama</artifactId></dependency></dependencies>该 starter 同时提供 Ollama Chat 和 Embedding 自动配置。Spring AI Ollama 文档
2. 模型配置
application.yml:
spring:ai:ollama:base-url:http://localhost:11434chat:options:model:qwen3:8btemperature:0.7embedding:options:model:qwen3-embedding:0.6b确保本地已经存在模型,模型下载详情见:https://blog.csdn.net/sinat_32502451/article/details/163534744
ollama pull qwen3:8b ollama pull qwen3-embedding:0.6b3. 使用 ChatClient 调用模型
packagecom.example.ai;importorg.springframework.ai.chat.client.ChatClient;importorg.springframework.stereotype.Service;importreactor.core.publisher.Flux;@ServicepublicclassAiChatService{privatefinalChatClientchatClient;publicAiChatService(ChatClient.BuilderchatClientBuilder){this.chatClient=chatClientBuilder.build();}/** * 同步调用模型。 */publicStringchat(Stringquestion){returnchatClient.prompt().user(question).call().content();}/** * 携带系统提示词调用模型。 */publicStringchat(StringsystemPrompt,Stringquestion){returnchatClient.prompt().system(systemPrompt).user(question).call().content();}/** * 流式调用模型。 */publicFlux<String>stream(Stringquestion){returnchatClient.prompt().user(question).stream().content();}}核心调用只有:
Stringanswer=chatClient.prompt().system("你是一个 Java 技术助手").user("介绍一下 Spring AI").call().content();各方法含义:
prompt():创建一次模型请求。system():设置系统提示词。user():设置用户消息。call():同步调用模型。stream():流式调用模型。content():取得模型返回的文本。
4. 提供 REST 接口
packagecom.example.ai;importorg.springframework.http.MediaType;importorg.springframework.web.bind.annotation.GetMapping;importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.bind.annotation.RequestParam;importorg.springframework.web.bind.annotation.RestController;importreactor.core.publisher.Flux;@RestController@RequestMapping("/api/ai")publicclassAiController{privatefinalAiChatServiceaiChatService;publicAiController(AiChatServiceaiChatService){this.aiChatService=aiChatService;}/** * 普通问答。 */@GetMapping("/chat")publicStringchat(@RequestParamStringquestion){returnaiChatService.chat(question);}/** * 流式问答。 */@GetMapping(value="/stream",produces=MediaType.TEXT_EVENT_STREAM_VALUE)publicFlux<String>stream(@RequestParamStringquestion){returnaiChatService.stream(question);}}普通调用:
curl'http://localhost:8080/api/ai/chat?question=介绍一下Spring%20AI'流式调用:
curl-N'http://localhost:8080/api/ai/stream?question=介绍一下Spring%20AI'5. 使用底层 ChatModel
ChatClient底层使用的是ChatModel。如果需要更直接地控制调用,可以直接注入:
packagecom.example.ai;importorg.springframework.ai.chat.model.ChatModel;importorg.springframework.ai.chat.model.ChatResponse;importorg.springframework.ai.chat.prompt.Prompt;importorg.springframework.stereotype.Service;@ServicepublicclassLowLevelChatService{privatefinalChatModelchatModel;publicLowLevelChatService(ChatModelchatModel){this.chatModel=chatModel;}/** * 直接通过 ChatModel 调用模型。 */publicStringchat(Stringquestion){Promptprompt=newPrompt(question);ChatResponseresponse=chatModel.call(prompt);returnresponse.getResult().getOutput().getText();}}也可以显式构造消息:
importjava.util.List;importorg.springframework.ai.chat.messages.SystemMessage;importorg.springframework.ai.chat.messages.UserMessage;importorg.springframework.ai.chat.model.ChatResponse;importorg.springframework.ai.chat.prompt.Prompt;SystemMessagesystemMessage=newSystemMessage("你是一个 Java 技术助手");UserMessageuserMessage=newUserMessage("Spring AI 是什么?");Promptprompt=newPrompt(List.of(systemMessage,userMessage));ChatResponseresponse=chatModel.call(prompt);Stringanswer=response.getResult().getOutput().getText();6. 调用 Embedding 模型
Spring Boot 同样会自动创建EmbeddingModel。Spring AI Ollama Embedding 文档
packagecom.example.ai;importjava.util.List;importorg.springframework.ai.embedding.EmbeddingModel;importorg.springframework.stereotype.Service;@ServicepublicclassAiEmbeddingService{privatefinalEmbeddingModelembeddingModel;publicAiEmbeddingService(EmbeddingModelembeddingModel){this.embeddingModel=embeddingModel;}/** * 将一段文本转换为向量。 */publicfloat[]embed(Stringtext){returnembeddingModel.embed(text);}/** * 批量将文本转换为向量。 */publicList<float[]>embedAll(List<String>texts){returnembeddingModel.embed(texts);}}使用:
float[]vector=aiEmbeddingService.embed("Spring AI 模型调用示例");System.out.println(vector.length);底层交互过程
Java 代码:
chatClient.prompt().user("你好").call().content();Spring AI 内部执行:
ChatClient ↓ OllamaChatModel ↓ 将 Prompt 转换成 Ollama JSON 请求 ↓ POST http://localhost:11434/api/chat ↓ Ollama 调用 qwen3:8b ↓ JSON 响应转换为 ChatResponse ↓ content() 返回文本Embedding 调用则是:
EmbeddingModel.embed(text) ↓ OllamaEmbeddingModel ↓ POST http://localhost:11434/api/embed ↓ qwen3-embedding:0.6b ↓ 返回 float[] 向量Java 业务代码本身是供应商无关的。以后切换到 OpenAI、Azure OpenAI 或其他模型时,通常只需要更换 starter 和application.yml,ChatClient、ChatModel、EmbeddingModel的调用代码可以保持不变。
资料
spring-ai官方文档: https://docs.spring.io/spring-ai/reference/index.html