本文将带你从零开始学习如何使用 Spring AI Alibaba,将强大的大模型能力集成到你的Spring Boot应用中。无论你是想开发智能客服、内容生成工具还是数据分析应用,本文都会提供完整的代码示例和详细步骤。
一、什么是 Spring AI Alibaba?
Spring AI Alibaba 是[阿里巴巴]开源的一个Spring Boot Starter模块,它让[Java开发]者可以轻松地在Spring应用中集成阿里云的通义千问等大模型。该项目封装了调用大模型API的复杂逻辑,开发者只需关注业务逻辑,而无需深入了解底层AI技术细节。
主要特性
- 支持多种阿里大模型(如Qwen系列)
 - 提供简洁易用的API接口
 - 自动化配置与依赖注入
 - 支持同步/异步调用
 - 可扩展性强,支持自定义模型接入
 
二、环境准备
在开始编码前,确保你的开发环境满足以下要求:
1. 技术栈要求
- JDK 17+ (Spring Boot 3.x要求)
 - Spring Boot 3.x 或 Spring Boot 2.7+
 - Maven 或 Gradle
 - 阿里云账号(用于获取API Key)
 
三、项目集成步骤
下面我们一步步创建集成Spring AI Alibaba的Spring Boot应用。
1. 创建项目并添加依赖
Maven配置
            
            
              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 
         http://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>3.2.0</version>
        <relativePath/>
    </parent>
    
    <groupId>com.example</groupId>
    <artifactId>spring-ai-demo</artifactId>
    <version>1.0.0</version>
    
    <properties>
        <java.version>17</java.version>
    </properties>
    
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        
        <!-- Spring AI Alibaba 核心依赖 -->
        <dependency>
            <groupId>com.alibaba.cloud.ai</groupId>
            <artifactId>spring-ai-alibaba-starter</artifactId>
            <version>1.0.0-M2</version>
        </dependency>
    </dependencies>
    
    <!-- 添加仓库配置 -->
    <repositories>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
        <repository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>https://repo.spring.io/snapshot</url>
            <releases>
                <enabled>false</enabled>
            </releases>
        </repository>
    </repositories>
</project>
AI写代码XML
        Gradle配置
            
            
              arduino
              
              
            
          
          implementation 'com.alibaba:spring-ai-alibaba-spring-boot-starter:0.8.0'
AI写代码
        2. 应用配置
在 application.yml 中添加以下配置
            
            
              yaml
              
              
            
          
          spring:
  ai:
    dashscope:
      api-key: your_api_key_here  # 替换为你的实际API Key
      chat:
        options:
          model: qwen-max  # 可选值: qwen-plus, qwen-turbo等
AI写代码html
        或者在 application.properties 中配置
            
            
              ini
              
              
            
          
          spring.ai.dashscope.api-key=${AI_DASHSCOPE_API_KEY}
AI写代码
        3. 创建聊天控制器
以下是完整的控制器实现,支持同步和流式响应
            
            
              kotlin
              
              
            
          
          package com.example.ai.controller;
 
import org.springframework.ai.chat.ChatClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
 
@RestController
@RequestMapping("/api/ai")
public class AIChatController {
    
    private final ChatClient chatClient;
    
    @Autowired
    public AIChatController(ChatClient chatClient) {
        this.chatClient = chatClient;
    }
    
    /**
     * 同步聊天接口 - 等待完整响应后返回
     */
    @GetMapping("/chat")
    public String chat(@RequestParam String message) {
        return chatClient.prompt()
                .user(message)
                .call()
                .content();
    }
    
    /**
     * 流式聊天接口 - 实时返回响应片段
     * 适用于长文本生成,实现打字机效果
     */
    @GetMapping("/chat/stream")
    public Flux<String> streamChat(@RequestParam String message) {
        return chatClient.prompt()
                .user(message)
                .stream()
                .content();
    }
}
AI写代码java
运行
        4. 创建服务类(可选)
对于更复杂的业务逻辑,建议使用服务层封装
            
            
              kotlin
              
              
            
          
          package com.example.ai.service;
 
import com.alibaba.spring.ai.alibaba.qwen.QwenChatClient;
import org.springframework.stereotype.Service;
 
@Service
public class AIChatService {
    
    private final QwenChatClient chatClient;
    
    public AIChatService(QwenChatClient chatClient) {
        this.chatClient = chatClient;
    }
    
    public String generateResponse(String prompt) {
        return chatClient.call(prompt);
    }
}
AI写代码java
运行
        四、进阶功能示例
1. 函数调用(Function Calling)
函数调用允许大模型动态触发业务逻辑,以下是天气查询工具示例
            
            
              kotlin
              
              
            
          
          package com.example.ai.tools;
 
import com.alibaba.spring.ai.tools.Tool;
import org.springframework.stereotype.Component;
 
@Component
public class WeatherTool {
    
    @Tool("get_weather")
    public String getWeather(String location) {
        // 这里可以集成真实的天气API
        return "当前" + location + "的天气是晴天,温度25°C";
    }
}
AI写代码java
运行
        注册工具到Qwen客户端:
            
            
              kotlin
              
              
            
          
          @Service
public class QwenService {
    private final QwenChatClient chatClient;
    
    public QwenService(QwenChatClient chatClient, WeatherTool weatherTool) {
        this.chatClient = chatClient;
        this.chatClient.setToolProviders(weatherTool);
    }
}
AI写代码java
运行
        当用户询问"明天上海天气如何?"时,Qwen会自动调用getWeather工具并返回整合后的信息。
2. 提示词模板(Prompt Template)
使用提示词模板可以构建更结构化的提示
            
            
              less
              
              
            
          
          @GetMapping("/professional")
public String professionalReply(@RequestParam String topic) {
    String systemPrompt = "你是一个专业的技术博客作者,请用通俗易懂的方式解释以下技术概念:";
    
    return chatClient.prompt()
            .system(systemPrompt)
            .user(topic)
            .call()
            .content();
}
AI写代码java
运行
        3. 图像生成示例
除了文本聊天,Spring AI Alibaba还支持图像生成
            
            
              less
              
              
            
          
          @RestController
@RequestMapping("/api/image")
public class ImageController {
    
    @Autowired
    private TongYiImagesModel imageClient;
    
    @GetMapping("/generate")
    public ResponseEntity<byte[]> generateImage(@RequestParam String prompt) {
        ImagePrompt imagePrompt = new ImagePrompt(prompt);
        ImageResponse response = imageClient.call(imagePrompt);
        String imageUrl = response.getResult().getOutput().getUrl();
        
        // 返回图像URL或直接返回图像数据
        return ResponseEntity.ok()
                .contentType(MediaType.IMAGE_PNG)
                .body(fetchImageData(imageUrl));
    }
}
AI写代码java
运行
        五、运行和测试
- 
启动Spring Boot应用
 - 
访问同步聊天接口:
bashhttp://localhost:8080/api/ai/chat?message=你好,请介绍一下Spring AI Alibaba AI写代码 - 
测试流式接口(使用HTTP客户端支持流式响应):
bashhttp://localhost:8080/api/ai/chat/stream?message=讲一个有趣的故事 AI写代码 
六、常见问题与解决方案
| 问题 | 解决方案 | 
|---|---|
| 报错 SignatureDoesNotMatch | 检查API Key是否正确,或重新生成 | 
| 请求超时 | 增加超时时间或检查网络连接 | 
| 返回空结果 | 检查输入内容是否合规,避免敏感词 | 
| 依赖解析失败 | 检查仓库配置,确保使用正确的Maven仓库 | 
七、实际应用场景
Spring AI Alibaba可以应用于多种业务场景
- 智能客服系统 - 自动回答用户问题
 - 内容生成工具 - 自动生成文章、产品描述等
 - 代码助手 - 帮助开发者编写和优化代码
 - 数据分析与总结 - 分析数据并生成自然语言报告
 
总结
通过本文的学习,你已经掌握了使用Spring AI Alibaba集成大模型的基本方法。这个框架大大降低了在Java应用中集成AI能力的门槛,让开发者可以专注于业务逻辑而不是底层技术细节。