导读:上一章我们使用 OpenAI 兼容模式接入了线上通义千问公有云模型,公有云存在调用计费、网络依赖、数据外传等问题。 本章带来私有化离线方案:Ollama,可以在本地电脑一键运行通义、Llama3、DeepSeek、ChatGLM 等数十款开源大模型。 依托稳定环境:JDK21 + Gradle8.8 + SpringBoot3.5.14 + SpringAI1.1.7,框架原生自带 Ollama 专属 Starter,无版本兼容坑。 全程不联网也能对话,数据全部留在本地;同时沿用统一ChatClient编码风格,和线上模型业务代码几乎一致,轻松实现云模型、本地模型一键切换。
一、环境前置说明
运行前提:电脑安装 Ollama客户端,提前拉取开源模型文件
适配环境清单
1. JDK:21
2. Gradle:8.8
3. SpringBoot:3.5.14
4. SpringAI:1.1.7
5. IDEA:2023 社区版
二、第一步:本地安装并启动 Ollama
# 轻量通义千问 2.5:7b,低配电脑流畅运行
ollama pull qwen2.5:7b
拉取完成后,Ollama 默认后台启动服务,地址固定:http://localhost:11434
- 当看到类似 >>> 的提示符时,输入任意问题(如“你好”或“1+1等于几”)。如果模型在几秒钟内给出了文字回复,且没有出现报错信息,就证明你的环境配置完全正确,可以正常调用了。
- 浏览器访问http://localhost:11434/ 页面会有返回信息
Ollama is running
三、build.gradle 引入 Ollama 依赖
覆盖原有配置,保留 web + ollama 双核心依赖
plugins {
id 'java'
id 'org.springframework.boot' version '3.5.14'
id 'io.spring.dependency-management' version '1.1.7'
}
dependencyManagement {
imports {
mavenBom "org.springframework.ai:spring-ai-bom:1.1.7" // 关键:通过BOM锁定所有Spring AI模块版本
}
}
group = 'com.example'
version = '0.0.1-SNAPSHOT'
java {
toolchain {
languageVersion = JavaLanguageVersion.of(21)
}
}
repositories {
maven { url 'https://maven.aliyun.com/nexus/content/groups/public' }
maven { url 'https://maven.aliyun.com/repository/google' }
mavenCentral()
// Spring AI 官方仓库
maven { url 'https://repo.spring.io/release' }
maven { url 'https://repo.spring.io/milestone' }
}
dependencies {
// 基础Web服务
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.ai:spring-ai-starter-model-ollama'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
}
tasks.named('test') {
useJUnitPlatform()
}
修改后点击 Gradle 面板 Reload All Gradle Projects 加载依赖。
四、application.yml Ollama 配置
路径:src/main/resources/application.yml
spring:
ai:
ollama:
base-url: http://localhost:11434 # Ollama 服务地址
chat:
model: qwen2.5:7b # 替换为已下载的模型名称
# 可选配置(提升生成质量)
temperature: 0.8
top-p: 0.95
max-tokens: 1024
踩坑: 请确保 application.yml 中配置的模型名称与 ollama list 显示的完全一致。否则会报类似错误
HTTP 404 – {“error”:“model ‘qwen2.5:7b’ not found”}
五、Controller 代码
package com.example.demo.controller;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/ai")
public class OllamaChatController {
private final ChatClient chatClient;
public OllamaChatController(ChatClient.Builder builder) {
this.chatClient = builder.build();
}
@GetMapping("/localChat")
public String localChat(@RequestParam String message) {
return chatClient.prompt(message)
.call()
.content();
}
}
六、启动项目并进行接口测试
浏览器访问
http://127.0.0.1:8080/ai/localChat?message=%E4%BB%8B%E7%BB%8D%E8%87%AA%E5%B7%B1
有正常响应返回 
七、常见问题排错
上一篇:SpringAI 实战 07|通过SpringAI接入通义千问



