一、简介
Spring Boot 4 + Spring 7 + IDEA 2025 + JDK17 ,Spring AI 的定位是:大模型基础对话 + RAG + MCP + Tool + Memory等基础功能。
Spring AI 2.0 新特性
- 传输协议发生了变化:去掉了Spring AI 1.0中的SSE模式(Server Send Events 单向长连接),使用新的模式(
MCP Streamable HTTP)。 - 在上层ChatClient增加
日志拦截器。 - 增加了Agent的模式:
观察思考 - 执行工具 - 反思迭代 - 验证确认。

应用场景
- 智能客服:在项目中嵌入一个聊天窗,然后通过Tool调用系统内部的Java方法以及通过MCP调用系统外部的功能(如网络搜索、地图、天气等第三方发布的API),原来通过用户点点点来实现的,现在通过聊天完成。
- RAG知识库。
二、项目打架
1. 添加依赖 pom.xml
SpringWeb + Spring AI + 第三方厂商(如 DeepSeek 、OpenAI、 Ollama):要考虑性能、成本、以及行业评分。

2. 配置application.properties
获取API Key(创建API Key): https://bailian.console.aliyun.com/cn-beijing?tab=model#/api-key

获取API Host: https://bailian.console.aliyun.com/cn-beijing?tab=api#/api/?type=app&url=2782167

示例代码(获取模型名称、base_url) https://bailian.console.aliyun.com/cn-beijing?tab=model#/model-market/detail/qwen3.7-plus?serviceSite=asia-pacific-china&ref=suggest

API Key配置在环境变量中。

properties
# 阿里百炼平台
spring.ai.deepseek.api-key=${DASHSCOPE_API_KEY}
spring.ai.deepseek.chat.model= qwen3.7-plus
spring.ai.deepseek.chat.base-url=https://llm-x2l5ucz6vk2xupzh.cn-beijing.maas.aliyuncs.com/compatible-mode/v1
logging.level.org.springframework.ai=DEBUG
环境变量配置完成后需要重启一下IDEA,否则环境变量加载不到。
3. Bean Configuration
java
@Configuration
public class SpringAiConfig {
@Bean
public ChatClient chatClient(DeepSeekChatModel deepSeekChatModel) {
return ChatClient.builder(deepSeekChatModel)
.defaultSystem("""
# 角色
你是一个教育行业的只能小助手
# 要求
1. 永远讲中文
""")
.build();
}
}
4. Controller测试
java
@RestController
public class SpringAIController {
@Autowired
private ChatClient chatClient;
@GetMapping(value = "/chat", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<String> chat(@RequestParam("message") String message) {
Flux<String> content = chatClient.prompt()
.user(message)
.stream()
.content()
.withConcat(Flux.just("[complete]")); // 自定义一个结束标记,前端解析到就不会再请求,表示本轮会话全部结束
return content;
}
}
