Spring AI 2.0:Hello World
2026/8/14 6:51:13 网站建设 项目流程

一、简介

Spring Boot 4 + Spring 7 + IDEA 2025 + JDK17 ,Spring AI 的定位是:大模型基础对话 + RAG + MCP + Tool + Memory等基础功能。

Spring AI 2.0 新特性

  1. 传输协议发生了变化:去掉了Spring AI 1.0中的SSE模式(Server Send Events 单向长连接),使用新的模式(MCP Streamable HTTP)。
  2. 在上层ChatClient增加日志拦截器
  3. 增加了Agent的模式:观察思考 - 执行工具 - 反思迭代 - 验证确认

应用场景

  1. 智能客服:在项目中嵌入一个聊天窗,然后通过Tool调用系统内部的Java方法以及通过MCP调用系统外部的功能(如网络搜索、地图、天气等第三方发布的API),原来通过用户点点点来实现的,现在通过聊天完成。
  2. 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

# 阿里百炼平台 spring.ai.deepseek.api-key=sk-3ac8885b9492111111111111111 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

3. Bean Configuration

@ConfigurationpublicclassSpringAiConfig{@BeanpublicChatClientchatClient(DeepSeekChatModeldeepSeekChatModel){returnChatClient.builder(deepSeekChatModel).defaultSystem(""" # 角色 你是一个教育行业的只能小助手 # 要求 1. 永远讲中文 """).build();}}

4. Controller测试

@RestControllerpublicclassSpringAIController{@AutowiredprivateChatClientchatClient;@GetMapping(value="/chat",produces=MediaType.TEXT_EVENT_STREAM_VALUE)publicFlux<String>chat(@RequestParam("message")Stringmessage){Flux<String>content=chatClient.prompt().user(message).stream().content().withConcat(Flux.just("[complete]"));// 自定义一个结束标记,前端解析到就不会再请求,表示本轮会话全部结束returncontent;}}

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询