引言
Spring Boot AI 是 Spring 官方推出的 AI 开发框架,简化了 Java 开发者集成大模型(如 OpenAI、Llama 3、Gemini 等)的流程;而 Spring Boot 4.0.1 作为最新稳定版,凭借原生镜像、Java 17+ 优化等特性,能让 AI 应用兼具「开发效率」与「运行性能」。本文将手把手教你在 Spring Boot 4.0.1 中集成 Spring Boot AI,覆盖「云端大模型调用」「本地模型部署」「Prompt 工程」等核心场景,所有代码均可直接复用。
1. 前置准备:环境与版本匹配
Spring Boot AI 与 Spring Boot 4.0.1 的版本兼容关键:
- 基础环境:JDK 17+(Spring Boot 4.0.1 强制要求)、Maven 3.8.8+ / Gradle 8.0+
- Spring Boot AI 版本:选择 0.8.1(最新稳定版,完美兼容 Spring Boot 4.0.1)
- 支持的 AI 模型:OpenAI (GPT-3.5/4o)、Azure OpenAI、Google Gemini、Ollama(本地模型,如 Llama 3、Qwen)、百度文心一言等
2. 快速集成:核心依赖配置
首先创建 Spring Boot 4.0.1 项目,在 pom.xml 中添加 Spring Boot AI 核心依赖(以 OpenAI 为例,其他模型仅需替换依赖):
xml
<?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>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>4.0.1</version>
<relativePath/>
</parent>
<groupId>com.example</groupId>
<artifactId>sb4-ai-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>sb4-ai-demo</name>
<dependencies>
<!-- Spring Boot Web 依赖(提供接口测试) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Spring Boot AI 核心依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-ai</artifactId>
<version>0.8.1</version>
</dependency>
<!-- Spring Boot AI OpenAI 适配依赖(调用云端 OpenAI 模型) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-ai-openai</artifactId>
<version>0.8.1</version>
</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>
<configuration>
<source>17</source>
<target>17</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
3. 核心场景实操
场景 1:调用云端 OpenAI 模型(GPT-3.5/4o)
这是最常用的场景,只需配置 API Key 即可快速调用 OpenAI 接口。
步骤 1:配置 OpenAI 密钥
在 application.yml 中添加 OpenAI 配置(替换为你的 API Key):
yaml
spring:
ai:
openai:
api-key: sk-xxxxxx # 你的 OpenAI API Key
base-url: https://api.openai.com/v1 # 官方地址(国内需代理可修改)
chat:
model: gpt-3.5-turbo # 模型名称,可选 gpt-4o、gpt-4-turbo 等
temperature: 0.7 # 随机性,0-1 之间,值越小越精准
步骤 2:编写 AI 调用代码
Spring Boot AI 提供了 OpenAiChatClient 封装类,可直接注入使用:
java
import org.springframework.ai.openai.OpenAiChatClient;
import org.springframework.ai.openai.api.OpenAiChatResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class OpenAIController {
// 注入 OpenAI 聊天客户端(Spring Boot AI 自动配置)
@Autowired
private OpenAiChatClient openAiChatClient;
/**
* 调用 OpenAI 生成回答
* @param prompt 提问内容
* @return AI 回答
*/
@GetMapping("/ai/chat")
public String chatWithOpenAI(@RequestParam String prompt) {
// 极简调用:直接传入 Prompt
return openAiChatClient.call(prompt);
// 进阶调用:自定义请求参数(如指定角色、温度)
/*
OpenAiChatRequest request = OpenAiChatRequest.builder()
.prompt(new Prompt(prompt))
.temperature(0.5)
.maxTokens(1000)
.build();
OpenAiChatResponse response = openAiChatClient.call(request);
return response.getResult().getOutput().getContent();
*/
}
}
步骤 3:测试接口
启动项目后,访问 http://localhost:8080/ai/chat?prompt=用Java写一个Spring Boot 4.0.1的HelloWorld,即可得到 AI 生成的代码回答。
场景 2:集成本地 LLM 模型(Ollama + Llama 3)
若想避免调用云端 API(数据隐私、网络限制),可通过 Ollama 部署本地模型(如 Llama 3、Qwen),Spring Boot AI 完美适配。
步骤 1:安装 Ollama 并启动 Llama 3
- 下载 Ollama:https://ollama.com/download
- 启动 Llama 3 模型(终端执行):
bash
# 拉取并启动 Llama 3 8B 模型
ollama run llama3
- 验证模型启动:访问
http://localhost:11434,返回Ollama API即成功。
步骤 2:配置本地模型依赖与参数
- 添加 Ollama 依赖到
pom.xml:
xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-ai-ollama</artifactId>
<version>0.8.1</version>
</dependency>
- 修改
application.yml配置:
yaml
spring:
ai:
ollama:
base-url: http://localhost:11434 # Ollama 本地地址
chat:
model: llama3 # 本地模型名称(与Ollama启动的模型一致)
temperature: 0.7
步骤 3:编写本地模型调用代码
只需替换注入的客户端为 OllamaChatClient,其余逻辑与云端一致:
java
import org.springframework.ai.ollama.OllamaChatClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class LocalAIController {
@Autowired
private OllamaChatClient ollamaChatClient;
@GetMapping("/ai/local/chat")
public String chatWithLocalLLM(@RequestParam String prompt) {
// 调用本地 Llama 3 模型
return ollamaChatClient.call(prompt);
}
}
场景 3:Prompt 工程与模板化
Spring Boot AI 支持 Prompt 模板,避免硬编码 Prompt,提升复用性。
步骤 1:定义 Prompt 模板
在 resources/prompts/ 下创建 code-generator.st 文件(ST 是 Spring AI 的模板后缀):
st
你是一个资深的 Java 开发工程师,请根据以下要求生成规范的代码:
1. 框架:Spring Boot 4.0.1
2. 功能:{{function}}
3. 要求:{{requirements}}
4. 输出格式:仅返回代码,无多余解释
步骤 2:使用模板调用 AI
java
import org.springframework.ai.prompt.Prompt;
import org.springframework.ai.prompt.PromptTemplate;
import org.springframework.ai.openai.OpenAiChatClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
@RestController
public class PromptTemplateController {
@Autowired
private OpenAiChatClient openAiChatClient;
@GetMapping("/ai/code/generate")
public String generateCode(
@RequestParam String function,
@RequestParam String requirements) {
// 加载 Prompt 模板
PromptTemplate promptTemplate = new PromptTemplate(
"classpath:prompts/code-generator.st");
// 填充模板参数
Map<String, Object> params = Map.of(
"function", function,
"requirements", requirements
);
Prompt prompt = promptTemplate.create(params);
// 调用 AI 生成代码
return openAiChatClient.call(prompt).getResult().getOutput().getContent();
}
}
测试:
访问 http://localhost:8080/ai/code/generate?function=用户登录接口&requirements=使用Spring Security,返回JSON格式,即可得到标准化的登录接口代码。
场景 4:结合 Spring Boot 4.0.1 原生镜像优化
Spring Boot 4.0.1 的原生镜像特性可让 AI 应用启动更快,只需添加原生镜像依赖并适配配置:
- 添加原生镜像依赖:
xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-native</artifactId>
</dependency>
- 构建原生镜像(需安装 GraalVM):
bash
mvn clean package -Pnative
- 启动原生应用:
bash
./target/sb4-ai-demo
注意:若调用本地 Ollama 模型,原生镜像无需额外配置;若调用云端 OpenAI,需确保 GraalVM 兼容 HTTP 客户端(Spring Boot AI 已自动适配)。
4. 关键注意事项与避坑指南
- 版本兼容:Spring Boot AI 0.8.1 是唯一稳定兼容 Spring Boot 4.0.1 的版本,切勿使用 0.7.x 及以下版本(会出现依赖冲突)。
- API Key 安全 :生产环境不要硬编码 API Key,可通过 Spring Boot 4.0.1 的
@ConfigurationProperties或环境变量注入:
yaml
spring:
ai:
openai:
api-key: ${OPENAI_API_KEY} # 从环境变量读取
- 本地模型性能 :Ollama 部署的本地模型(如 Llama 3 70B)对硬件要求较高(建议 16G 以上内存),可通过
num_ctx参数限制上下文长度优化性能:
yaml
spring:
ai:
ollama:
chat:
options:
num_ctx: 2048 # 限制上下文长度为2048 tokens
- Jakarta EE 适配 :Spring Boot 4.0.1 基于 Jakarta EE 10,Spring Boot AI 已完全适配,无需修改
javax.*包名(内部已替换为jakarta.*)。
三、总结
核心要点回顾
- 集成核心:Spring Boot 4.0.1 集成 Spring Boot AI 只需添加对应模型依赖(OpenAI/Ollama)+ 配置 API/本地模型地址,即可快速调用大模型;
- 核心场景:云端模型调用(极简 API)、本地模型部署(Ollama + Llama 3)、Prompt 模板化(提升复用性)、原生镜像优化(适配云原生);
- 避坑关键:版本匹配(Spring Boot AI 0.8.1)、API Key 安全、本地模型性能调优。
通过 Spring Boot 4.0.1 + Spring Boot AI 的组合,你可以快速构建「高性能、易维护、可扩展」的 AI 应用,无论是调用云端大模型还是部署本地模型,都能兼顾开发效率与运行性能。如果需要集成更多模型(如百度文心一言、阿里云通义千问),可在评论区留言,我会补充对应的配置示例~