⭐⭐⭐ Spring Boot 项目实战 ⭐⭐⭐ Spring Cloud 项目实战
《Dubbo 实现原理与源码解析 —— 精品合集》 《Netty 实现原理与源码解析 —— 精品合集》
《Spring 实现原理与源码解析 —— 精品合集》 《MyBatis 实现原理与源码解析 —— 精品合集》
《Spring MVC 实现原理与源码解析 —— 精品合集》 《数据库实体设计合集》
《Spring Boot 实现原理与源码解析 —— 精品合集》 《Java 面试题 + Java 学习指南》

摘要: 原创出处 blog.csdn.net/weixin_68138311 「在努力的韩小豪」欢迎转载,保留摘要,谢谢!


🙂🙂🙂关注微信公众号:【芋道源码】有福利:

  1. RocketMQ / MyCAT / Sharding-JDBC 所有源码分析文章列表
  2. RocketMQ / MyCAT / Sharding-JDBC 中文注释源码 GitHub 地址
  3. 您对于源码的疑问每条留言都将得到认真回复。甚至不知道如何读源码也可以请教噢。
  4. 新的源码解析文章实时收到通知。每周更新一篇左右。
  5. 认真的源码交流微信群。

一、前言

Spring Boot

  • 简化 Spring 应用开发的框架;
  • 通过自动配置、内嵌服务器(如 Tomcat)和约定优于配置的原则,让开发者快速构建独立、生产级的应用。

Spring AI

  • Spring AI 是 Spring 生态中集成 AI 能力的模块;
  • 旨在简化大语言模型(LLM)、生成式 AI 服务的调用,提供统一的 API 抽象层,支持 OpenAI、Azure AI、Hugging Face 等主流 AI 服务。

二、具体实现(Spring Boot + Spring AI的简单应用)

1.环境准备

  • JDK 17+
  • Maven 3.6+
  • OpenAI API Key(在平台.openai.com获取)

2.项目初始化

  • 使用 start.spring.io 生成项目,选择依赖:

    • Spring Web
    • Spring AI (选择对应版本)
  • 或直接在pom.xml中添加依赖:

<!-- Spring AI OpenAI -->
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-openai-spring-boot-starter</artifactId>
<version>0.8.1</version> <!-- 使用最新版本 -->
</dependency>

<!-- Spring Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

3.配置OpenAI API Key

在application.properties / yml中配置:

# OpenAI配置
spring.ai.openai.api-key=your-api-key-here
spring.ai.openai.chat.options.model=gpt-3.5-turbo

4.创建Controller

import org.springframework.ai.chat.ChatClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
publicclassAIController {

privatefinal ChatClient chatClient;

// 构造器注入
publicAIController(ChatClient chatClient) {
this.chatClient = chatClient;
}

@GetMapping("/ai/chat")
public String chat(@RequestParam String message) {
return chatClient.call(message);
}
}

5.进阶:自定义Prompt模板【提示词工程】

创建更结构化的提示词模板【提示词工程】,方便AI理解和推理

import org.springframework.ai.chat.prompt.PromptTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

@PostMapping("/ai/translate")
public String translate(@RequestBody TranslationRequest request) {
PromptTemplatepromptTemplate=newPromptTemplate("""
将以下{sourceLang}文本翻译成{targetLang}:
{text}
""");

promptTemplate.add("sourceLang", request.sourceLang());
promptTemplate.add("targetLang", request.targetLang());
promptTemplate.add("text", request.text());

return chatClient.call(promptTemplate.render());
}

// DTO:名为 TranslationRequest 的记录类(record),用于存储翻译请求的信息
// 该记录类通常用于封装翻译 API 请求所需的数据
recordTranslationRequest(String sourceLang, String targetLang, String text) {}

6.运行应用

通过命令行或开发工具启动Spring Boot项目

7.接口测试

1)/ai/chat 接口

a.在浏览器或接口测试工具中输入URL:

http://localhost:8080/ai/chat?message=用Java写一个Hello World程序

b.页面输出的内容:成功响应(HTTP 200 OK)

public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}

2) /ai/translate 接口

a.在接口测试工具(如Postman、ApiFox)中输入以下信息:

// json
{
"sourceLang": "中文",
"targetLang": "英文",
"text": "今天天气真好"
}

b.接口返回的响应内容:成功响应(HTTP 200 ok)

// text
"Today's weather is really nice."

8.高级配置

在application.properties / yml中添加更多参数:

# 控制生成内容
spring.ai.openai.chat.options.temperature=0.7
spring.ai.openai.chat.options.max-tokens=500

9.异常处理

全局异常捕获和处理:

import org.springframework.ai.openai.api.OpenAiApiException;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class GlobalExceptionHandler {

@ExceptionHandler(OpenAiApiException.class)
public ResponseEntity<String> handleOpenAiError(OpenAiApiException ex) {
return ResponseEntity.status(ex.getStatusCode())
.body("AI服务错误: " + ex.getMessage());
}
}

10.完整项目结构

src/main/java
└── com.example
└── aiapp
├── AIController.java
├── GlobalExceptionHandler.java
└── AiAppApplication.java (主类)

11.关键点说明

  • 依赖管理: Spring AI的starter包简化了与AI服务的集成
  • 自动配置: ChatClient会自动注入配置好的OpenAI客户端
  • 模板引擎: PromptTemplate支持动态提示词生成
  • 可扩展性: 可轻松切换不同AI提供商(如Azure OpenAI)

三、拓展

1.错误场景示例

API Key 无效时的响应:

// json
{
"status": 401,
"error": "Unauthorized",
"message": "AI服务错误: Invalid API Key"
}
  • 字段缺失: 若请求体缺少 sourceLang 或 text 字段,会返回 400 Bad Request 错误。
  • 语言不支持: 若指定语言(如 targetLang: 火星文)模型不支持,返回‘无法完成翻译’提示。

2.实际输出可能不同

翻译结果会因模型版本(如 gpt-3.5-turbo 或 gpt-4)和参数(如 temperature)略有差异。

示例是典型结果,但可能返回类似 “The weather is very nice today.” 的变体。

3.流式响应(高级功能)

如果需要实时逐字输出(类似 ChatGPT),交互更友好,可以改用 StreamingChatClient:

@GetMapping("/ai/chat-stream")
public Flux<String> chatStream(@RequestParam String message) {
return streamingChatClient.stream(message);
}

4.超长文本处理

文本过长(超过模型 token 限制)时响应会被截断;

需在 application.properties 中调整 max-tokens 参数:

spring.ai.openai.chat.options.max-tokens=2000

5.内容返回格式

默认返回纯文本(text/plain),若希望返回 JSON 格式,可在 Controller 中修改响应类型:

@PostMapping(value = "/ai/translate", produces = "application/json")  
public Map<String, String> translate(...) {
return Map.of("result", translatedText);
}

响应示例:

// json
{ "result": "Today's weather is really nice." }

6.附加测试建议

接口开发完成后,建议多使用几个请求进行测试:

1)提供其他需求:http://localhost:8080/ai/chat?message=用Python写一个斐波那契数列函数

def fibonacci(n):
a, b = 0, 1
for _ in range(n):
print(a)
a, b = b, a + b

2)翻译不同语种:修改请求体中的sourceLang和targetLang

// json
{
"sourceLang":"英文",
"targetLang":"法语",
"text":"Hello, how are you?"
}

预期响应输出:

"Bonjour, comment allez-vous ?"

四、总结和趋势

  • Spring Boot 是构建现代 Java 应用的基石,而Spring AI 是其生态中专注于 AI 集成的利器。
  • 两者结合可快速实现“传统业务 + AI 增强”的架构,例如智能客服、文档分析、代码生成等场景。
  • Spring AI 将更注重开放性(多模型支持)、性能(低延迟流式响应)和企业级能力(安全、监控),成为 Java 生态中 AI 应用开发的首选框架。

未来趋势:

1)技术方向

  • 多模态支持: 从文本生成扩展到图像、语音、视频等多模态 AI 能力。
  • 本地模型集成: 优化对本地运行的大模型(如 Llama.cpp,Ollama)的支持,降低云端依赖。
  • 流式响应优化: 提升实时交互场景下的性能(如 StreamingChatClient)。

2)生态扩展

  • 更多 AI 服务商: 兼容新兴模型(如 Google Gemini、Anthropic Claude)。
  • 企业级工具链: 与 Spring Security、Spring Cloud 深度集成,提供企业级 AI 应用的鉴权、限流、熔断能力。
  • 低代码整合: 结合 Spring Boot 的快速开发特性,提供可视化 AI 编排工具。

3)行业应用

  • 垂直领域解决方案: 针对金融、医疗、教育等行业定制 Prompt 模板和评估工具。
  • AI Agent 框架: 支持构建自主决策的 AI Agent 系统(如任务分解、工具调用)。
文章目录
  1. 1. 一、前言
    1. 1.1. Spring Boot
    2. 1.2. Spring AI
  2. 2. 二、具体实现(Spring Boot + Spring AI的简单应用)
    1. 2.1. 1.环境准备
    2. 2.2. 2.项目初始化
    3. 2.3. 3.配置OpenAI API Key
    4. 2.4. 4.创建Controller
    5. 2.5. 5.进阶:自定义Prompt模板【提示词工程】
    6. 2.6. 6.运行应用
    7. 2.7. 7.接口测试
      1. 2.7.1. 1)/ai/chat 接口
      2. 2.7.2. 2) /ai/translate 接口
    8. 2.8. 8.高级配置
    9. 2.9. 9.异常处理
    10. 2.10. 10.完整项目结构
    11. 2.11. 11.关键点说明
  3. 3. 三、拓展
    1. 3.1. 1.错误场景示例
    2. 3.2. 2.实际输出可能不同
    3. 3.3. 3.流式响应(高级功能)
    4. 3.4. 4.超长文本处理
    5. 3.5. 5.内容返回格式
    6. 3.6. 6.附加测试建议
  4. 4. 四、总结和趋势
    1. 4.1. 未来趋势:
      1. 4.1.1. 1)技术方向
      2. 4.1.2. 2)生态扩展
      3. 4.1.3. 3)行业应用