如果你是一名Java开发者最近可能已经感受到了AI技术带来的冲击大模型不再是遥不可及的实验室产品而是正在快速渗透到企业级应用开发中。但问题也随之而来——如何将现有的Java技术栈与AI能力无缝集成如何避免重复造轮子快速构建具备智能能力的应用这正是Spring AI 2.0要解决的核心问题。作为Spring生态在AI领域的重要布局Spring AI 2.0不仅提供了与大模型交互的标准API更重要的是引入了MCPModel Context Protocol这一革命性协议让Java开发者能够以开箱即用的方式集成各种AI工具和能力。1. 为什么Spring AI 2.0值得每个Java开发者关注传统AI应用开发面临的最大痛点就是重复造轮子。每个项目都需要从零开始对接各种API、处理数据格式转换、实现工具调用逻辑。而Spring AI 2.0通过MCP协议彻底改变了这一现状。MCP可以理解为AI世界的USB标准协议。它定义了一套标准化的接口规范让不同的AI工具和服务能够即插即用。无论是地图服务、代码仓库操作、数据库查询还是其他第三方服务只要遵循MCP协议就能被任何支持MCP的AI应用直接调用。这种设计带来的直接好处是降低开发门槛无需深入理解每个工具的具体API细节提高代码复用性一次开发的MCP服务可以被多个AI应用共享使用标准化交互流程统一的工具发现、调用和错误处理机制2. MCP协议的核心概念与架构解析2.1 MCP的基本工作原理MCP协议的核心思想是将AI应用客户端与具体的能力服务服务端解耦。整个架构包含三个关键角色MCP客户端通常是AI应用本身如基于Spring AI构建的智能体MCP服务端提供具体能力的服务如天气查询、地图服务、代码仓库操作等MCP协议定义客户端与服务端之间的通信规范工作流程如下客户端启动时发现可用的MCP服务客户端获取服务端提供的工具列表和参数定义用户提问时AI模型判断需要调用哪些工具客户端通过MCP协议调用相应工具并获取结果客户端将工具返回的结果整合到最终回答中2.2 MCP的两种通信模式Spring AI支持两种MCP通信模式适应不同的部署场景stdio模式标准输入输出服务端作为子进程被客户端启动通过标准输入输出流进行通信适合本地开发和小型部署场景SSE模式Server-Sent Events服务端作为独立的HTTP服务运行客户端通过HTTP请求调用远程服务适合生产环境和微服务架构3. 环境准备与项目搭建3.1 基础环境要求开始之前确保你的开发环境满足以下要求Java 17或更高版本Spring AI 2.0需要Java 17支持Maven 3.6或Gradle 7.x构建工具Spring Boot 3.2基础框架IDE推荐IntelliJ IDEA或VS Code with Java插件3.2 创建Spring Boot项目使用Spring Initializr快速创建项目基础结构# 使用curl创建项目 curl https://start.spring.io/starter.zip \ -d dependencieswebflux,ai \ -d typemaven-project \ -d languagejava \ -d bootVersion3.2.0 \ -d baseDirspring-ai-mcp-demo \ -d groupIdcom.example \ -d artifactIdai-demo \ -o spring-ai-mcp-demo.zip # 解压并进入项目目录 unzip spring-ai-mcp-demo.zip cd spring-ai-mcp-demo或者直接在IDE中使用Spring Initializr创建包含WebFlux和Spring AI依赖的项目。3.3 添加MCP相关依赖在pom.xml中添加Spring AI MCP依赖dependencies !-- Spring AI 核心依赖 -- dependency groupIdorg.springframework.ai/groupId artifactIdspring-ai-bom/artifactId version1.0.0-M6/version typepom/type scopeimport/scope /dependency !-- MCP客户端依赖 -- dependency groupIdorg.springframework.ai/groupId artifactIdspring-ai-mcp-client-spring-boot-starter/artifactId /dependency !-- WebFlux用于SSE模式 -- dependency groupIdorg.springframework.boot/groupId artifactIdspring-boot-starter-webflux/artifactId /dependency /dependencies4. 构建你的第一个MCP服务端4.1 基于stdio的天气查询服务我们先创建一个简单的天气查询MCP服务端使用stdio通信模式。创建服务端项目结构mkdir mcp-weather-server cd mcp-weather-server添加MCP服务端依赖pom.xmldependencies dependency groupIdorg.springframework.ai/groupId artifactIdspring-ai-mcp-server-spring-boot-starter/artifactId version1.0.0-M6/version /dependency dependency groupIdorg.springframework.boot/groupId artifactIdspring-boot-starter-webflux/artifactId /dependency /dependencies配置应用属性application.ymlspring: main: web-application-type: none # 禁用Web应用类型 banner-mode: off # 禁用banner ai: mcp: server: stdio: true # 启用stdio模式 name: weather-server # 服务名称 version: 1.0.0 # 服务版本实现天气查询工具package com.example.weather.service; import org.springframework.ai.tool.Tool; import org.springframework.ai.tool.ToolParameter; import org.springframework.stereotype.Service; import org.springframework.web.reactive.function.client.WebClient; import reactor.core.publisher.Mono; Service public class WeatherService { private final WebClient webClient; public WeatherService(WebClient.Builder webClientBuilder) { this.webClient webClientBuilder .baseUrl(https://api.open-meteo.com/v1) .build(); } Tool(description 根据经纬度获取天气预报信息) public String getWeatherForecast( ToolParameter(description 纬度例如39.9042) String latitude, ToolParameter(description 经度例如116.4074) String longitude) { try { String response webClient.get() .uri(uriBuilder - uriBuilder .path(/forecast) .queryParam(latitude, latitude) .queryParam(longitude, longitude) .queryParam(current, temperature_2m,wind_speed_10m) .queryParam(timezone, auto) .build()) .retrieve() .bodyToMono(String.class) .block(); return formatWeatherResponse(latitude, longitude, response); } catch (Exception e) { return 获取天气信息失败 e.getMessage(); } } Tool(description 根据城市名称获取空气质量信息) public String getAirQuality(ToolParameter(description 城市名称) String city) { // 模拟空气质量数据实际项目中应调用真实API return String.format( %s的空气质量信息 - PM2.5: 35 μg/m³ (良) - PM10: 50 μg/m³ (良) - 空气质量指数(AQI): 65 (良) - 主要污染物: 颗粒物(PM2.5) , city); } private String formatWeatherResponse(String lat, String lng, String apiResponse) { // 简化处理实际应解析JSON响应 return String.format( 位置纬度%s经度%s的天气信息 %s , lat, lng, apiResponse); } }注册工具Beanpackage com.example.weather; import com.example.weather.service.WeatherService; import org.springframework.ai.mcp.server.ToolCallbackProvider; import org.springframework.ai.mcp.server.MethodToolCallbackProvider; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; SpringBootApplication public class WeatherServerApplication { public static void main(String[] args) { SpringApplication.run(WeatherServerApplication.class, args); } Bean public ToolCallbackProvider weatherTools(WeatherService weatherService) { return MethodToolCallbackProvider.builder() .toolObjects(weatherService) .build(); } }打包并测试服务端mvn clean package -DskipTests java -jar target/mcp-weather-server-1.0.0.jar5. 构建MCP客户端应用5.1 配置MCP客户端在客户端项目的application.yml中配置MCP服务spring: ai: openai: api-key: ${OPENAI_API_KEY} # 设置你的OpenAI API密钥 mcp: client: stdio: servers-configuration: classpath:/mcp-servers-config.json创建MCP服务配置文件src/main/resources/mcp-servers-config.json{ mcpServers: { weather: { command: java, args: [ -Dspring.ai.mcp.server.stdiotrue, -Dspring.main.web-application-typenone, -jar, /path/to/your/mcp-weather-server.jar ], env: {} } } }5.2 实现客户端调用逻辑package com.example.client; import org.springframework.ai.chat.client.ChatClient; import org.springframework.ai.chat.model.ChatModel; import org.springframework.ai.mcp.client.ToolCallbackProvider; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.Bean; SpringBootApplication public class McpClientApplication { public static void main(String[] args) { SpringApplication.run(McpClientApplication.class, args); } Bean public CommandLineRunner demoChat( ChatClient.Builder chatClientBuilder, ToolCallbackProvider toolCallbackProvider, ConfigurableApplicationContext context) { return args - { var chatClient chatClientBuilder .defaultTools(toolCallbackProvider) .build(); // 测试天气查询 String weatherQuery 北京今天的天气怎么样; System.out.println(用户问题: weatherQuery); String weatherResponse chatClient.prompt(weatherQuery) .call() .content(); System.out.println(AI回答: weatherResponse); System.out.println(----------------------------------------); // 测试空气质量查询 String airQualityQuery 上海的空气质量如何; System.out.println(用户问题: airQualityQuery); String airQualityResponse chatClient.prompt(airQualityQuery) .call() .content(); System.out.println(AI回答: airQualityResponse); context.close(); }; } }5.3 运行完整示例启动客户端应用mvn spring-boot:run -Dspring-boot.run.arguments--OPENAI_API_KEYyour_api_key_here如果一切正常你将看到类似以下的输出用户问题: 北京今天的天气怎么样 AI回答: 根据查询结果北京当前天气情况如下 温度: 15.2°C风速: 3.5m/s天气状况: 晴朗 用户问题: 上海的空气质量如何 AI回答: 上海当前的空气质量指数为65等级为良主要污染物为PM2.56. 高级特性在OpenManus中集成MCPOpenManus是Spring AI Alibaba提供的智能体框架可以更复杂地编排多个工具调用。下面演示如何在OpenManus中集成MCP服务。6.1 添加OpenManus依赖dependency groupIdorg.springframework.ai/groupId artifactIdspring-ai-openmanus-spring-boot-starter/artifactId version1.0.0-M6/version /dependency6.2 配置百度地图MCP服务首先申请百度地图API密钥然后配置MCP服务{ mcpServers: { baidu-map: { command: npx, args: [ -y, baidumap/mcp-server-baidu-map ], env: { BAIDU_MAP_API_KEY: your_baidu_map_api_key } } } }6.3 实现路线规划功能package com.example.manus; import org.springframework.ai.chat.client.ChatClient; import org.springframework.ai.chat.model.ChatModel; import org.springframework.ai.mcp.client.ToolCallbackProvider; import org.springframework.ai.openmanus.annotation.Agent; import org.springframework.ai.openmanus.annotation.AgentService; import org.springframework.beans.factory.annotation.Autowired; AgentService public class RoutePlanningService { private final ChatClient routeChatClient; Autowired public RoutePlanningService(ChatModel chatModel, ToolCallbackProvider toolCallbackProvider) { this.routeChatClient ChatClient.builder(chatModel) .defaultTools(toolCallbackProvider) .defaultSystem(你是一个专业的路线规划助手能够使用地图工具为用户规划最佳路线。) .build(); } Agent(name routePlanner, description 路线规划智能体) public String planRoute(String startCity, String endCity) { String query String.format(规划从%s到%s的驾车路线, startCity, endCity); return routeChatClient.prompt(query) .call() .content(); } }6.4 测试路线规划Bean public CommandLineRunner testRoutePlanning(RoutePlanningService routeService) { return args - { String result routeService.planRoute(北京, 上海); System.out.println(路线规划结果: result); }; }运行后将获得详细的路线规划信息包括距离、预计时间和主要途径道路。7. 常见问题与解决方案7.1 依赖冲突问题问题现象Caused by: java.lang.IllegalStateException: Multiple tools with the same name解决方案 排除冲突的自动配置类SpringBootApplication(exclude { org.springframework.ai.autoconfigure.mcp.client.SseHttpClientTransportAutoConfiguration.class }) public class Application { // ... }7.2 MCP服务连接失败问题现象Failed to start MCP server: Connection refused排查步骤检查MCP服务jar路径是否正确确认Java环境变量配置验证服务端是否独立运行正常解决方案{ mcpServers: { weather: { command: java, args: [ -jar, /absolute/path/to/mcp-weather-server.jar ] } } }7.3 API密钥配置错误问题现象Authentication failed for API key解决方案 确保环境变量正确设置export OPENAI_API_KEYyour_actual_key # 或者使用application.yml配置8. 生产环境最佳实践8.1 安全配置API密钥管理spring: ai: openai: api-key: ${AI_API_KEY} # 从环境变量读取MCP服务认证Bean public WebClient.Builder secureWebClientBuilder() { return WebClient.builder() .filter((request, next) - { // 添加认证头 ClientRequest filtered ClientRequest.from(request) .header(Authorization, Bearer apiKey) .build(); return next.exchange(filtered); }); }8.2 性能优化连接池配置spring: ai: mcp: client: sse: connection-timeout: 30s read-timeout: 60s异步处理Async public CompletableFutureString asyncWeatherQuery(String location) { return CompletableFuture.supplyAsync(() - chatClient.prompt(查询 location 天气).call().content() ); }8.3 监控与日志添加详细日志Slf4j Service public class MonitoringService { public void logToolUsage(String toolName, Duration executionTime) { log.info(工具 {} 执行时间: {} ms, toolName, executionTime.toMillis()); } }健康检查Component public class McpHealthIndicator implements HealthIndicator { Override public Health health() { // 检查MCP服务连接状态 return Health.up().withDetail(mcp-services, 3 connected).build(); } }9. 实际项目应用场景9.1 智能客服系统结合MCP服务构建多能力客服机器人public class CustomerServiceAgent { public String handleCustomerQuery(String query) { // 自动判断需要调用哪些MCP服务 // 如订单查询、物流跟踪、产品信息等 return chatClient.prompt(query) .tools(orderTool, logisticsTool, productTool) .call() .content(); } }9.2 数据分析平台集成多种数据源进行智能分析public class DataAnalysisService { public String analyzeBusinessData(String requirement) { // 调用数据库查询、图表生成、报告编写等MCP服务 return chatClient.prompt(requirement) .tools(dbQueryTool, chartTool, reportTool) .call() .content(); } }通过本文的实战演示你应该已经掌握了使用Spring AI 2.0和MCP协议构建智能Java应用的核心技能。关键在于理解MCP的即插即用理念将复杂的能力封装成标准化的工具服务让AI应用能够专注于业务逻辑而非技术细节。随着AI技术的快速发展掌握Spring AI和MCP将成为Java开发者的一项重要竞争力。建议从简单的工具服务开始逐步构建复杂的企业级AI应用在实际项目中不断积累经验。