【SpringAi最新版入门(一)】

张开发
2026/7/2 2:31:50 15 分钟阅读
【SpringAi最新版入门(一)】
随着大模型技术的普及越来越多的Java后端开发者希望将AI能力集成到自身的SpringBoot项目中但面临着诸多痛点官方文档更新迭代频繁不同版本的API差异较大新手难以快速定位适配最新版的核心用法部分入门资料停留在旧版本复制代码后频繁出现依赖冲突、配置报错等问题AI底层逻辑复杂开发者无需深入研究模型原理却找不到贴合Spring生态习惯的集成方式。基于此本文专门整理了Spring AI最新版入门Demo核心目的的的是为CSDN广大Java开发者、Spring生态学习者提供一套“零门槛、可直接运行、贴合实战”的入门指南快速入门1.运行ollama下载大模型2.建一个springboot项目我使用的项目环境是JDK21,springboot的版本是3.5.13选中AI中的ollama,点击创建项目3.编写Controller和配置类package com.springai; import org.springframework.ai.chat.client.ChatClient; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; RestController RequestMapping(/ai) public class Controller { Autowired private ChatClient chatClient; GetMapping(/chat) public String chat(RequestParam String prompt) { return chatClient.prompt(prompt).call().content(); } }package com.springai; import org.springframework.ai.chat.client.ChatClient; import org.springframework.ai.ollama.OllamaChatModel; import org.springframework.ai.ollama.api.OllamaApi; import org.springframework.ai.ollama.api.OllamaChatOptions; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; Configuration public class AiConfig { Bean public OllamaChatModel ollamaChatModel() { return OllamaChatModel.builder() .ollamaApi(new OllamaApi.Builder() .baseUrl(http://localhost:11434) .build() ) .defaultOptions(OllamaChatOptions.builder() .model(deepseek-r1:7b) .temperature(0.7) .build()) .build(); } Bean public ChatClient chatClient(OllamaChatModel model) { return ChatClient.builder(model).build(); } }4.最后启动项目打开浏览器访问http://localhost:8080/ai/chat?prompt%E4%BD%A0%E6%98%AF%E8%B0%81结果如下

更多文章