SpringBoot集成Spring AI构建AI智能客服模块

 更新时间:2026年04月28日 09:08:51   作者:大龄码农-涵哥  
本文介绍了如何在SpringBoot项目中集成AI能力,包括创建项目、配置API密钥、开发AI对话服务以及测试验证,重点在于通过简单的示例展示AI对话的基本实现,为后续更复杂的进阶功能铺垫基础,需要的朋友可以参考下

一、前言

Spring Boot是Java最主流的框架,Spring官方也适时推出了Spring AI项目,让我们可以在Spring Boot应用中轻松集成AI能力。本文手把手教你搭建一个AI智能客服模块。

二、创建Spring Boot项目

2.1 使用Spring Initializr创建项目

访问 https://start.spring.io/ ,勾选以下依赖:

  • Spring Web
  • Spring AI(2024版本)
  • Thymeleaf(可选,用于简单页面展示)

2.2 配置pom.xml

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>3.2.4</version>
</parent>
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!-- Spring AI OpenAI -->
    <dependency>
        <groupId>org.springframework.ai</groupId>
        <artifactId>spring-ai-openai-spring-boot-starter</artifactId>
        <version>2024.0.0.0</version>
    </dependency>
</dependencies>

三、配置API Key

application.yml 中配置:

OpenAI配置

spring:
  ai:
    openai:
      api-key: ${OPENAI_API_KEY}
      chat:
        options:
          model: gpt-3.5-turbo
          temperature: 0.7

阿里通义千问配置

spring:
  ai:
    dashscope:
      api-key: ${DASHSCOPE_API_KEY}
      chat:
        options:
          model: qwen-turbo

四、开发AI对话服务

4.1 Service层

package com.example.ai.service;

import org.springframework.ai.chat.*;
import org.springframework.ai.chat.messages.*;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class AIService {

    private final ChatClient chatClient;

    public AIService(ChatClient chatClient) {
        this.chatClient = chatClient;
    }

    /**
     * 简单对话(无上下文)
     */
    public String chat(String userMessage) {
        return chatClient.call(userMessage);
    }

    /**
     * 带上下文的对话(记住对话历史)
     */
    public String chatWithContext(String userMessage, ChatMemory chatMemory) {
        UserMessage userMsg = new UserMessage(userMessage);
        ChatResponse response = chatClient.call(
            new Prompt(
                List.of(userMsg),
                ChatOptions.builder()
                    .model("gpt-3.5-turbo")
                    .temperature(0.7f)
                    .build()
            )
        );
        return response.getResult().getOutput().getText();
    }

    /**
     * 系统提示词(设定AI角色)
     */
    public String chatAsCustomerService(String userMessage) {
        SystemPromptTemplate systemPrompt = new SystemPromptTemplate("""
            你是一个专业的电商客服,名字叫小e。
            你的职责是:
            1. 热情友好地回复客户咨询
            2. 了解客户需求,给出专业建议
            3. 引导客户下单,解答售后问题
            
            请用简洁、亲切的语言回复。
            """);
        
        UserMessage userMsg = new UserMessage(userMessage);
        Prompt prompt = new Prompt(List.of(userMsg));
        
        return chatClient.call(prompt).getResult().getOutput().getText();
    }
}

4.2 Controller层

package com.example.ai.controller;

import com.example.ai.service.AIService;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/ai")
public class AIController {

    private final AIService aiService;

    public AIController(AIService aiService) {
        this.aiService = aiService;
    }

    /**
     * 普通对话接口
     * 调用示例:GET /api/ai/chat?message=这件商品有优惠吗
     */
    @GetMapping("/chat")
    public String chat(@RequestParam String message) {
        return aiService.chat(message);
    }

    /**
     * 扮演客服角色对话
     */
    @GetMapping("/customer-service")
    public String customerService(@RequestParam String message) {
        return aiService.chatAsCustomerService(message);
    }

    /**
     * POST请求,支持JSON body
     */
    @PostMapping("/chat")
    public String chatPost(@RequestBody ChatRequest request) {
        return aiService.chatAsCustomerService(request.getMessage());
    }
}

class ChatRequest {
    private String message;
    public String getMessage() { return message; }
    public void setMessage(String message) { this.message = message; }
}

五、测试验证

5.1 启动应用

mvn spring-boot:run

5.2 接口测试

# 普通对话
curl "http://localhost:8080/api/ai/chat?message=Java如何定义变量"
# 客服角色对话
curl "http://localhost:8080/api/ai/customer-service?message=这件裙子有几种颜色"

5.3 Postman测试

POST http://localhost:8080/api/ai/chat
Content-Type: application/json

{
    "message": "你们的退货政策是怎样的?"
}

到此这篇关于SpringBoot集成Spring AI构建AI智能客服模块的文章就介绍到这了,更多相关SpringBoot AI智能客服模块内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • java实现一致性hash算法实例代码

    java实现一致性hash算法实例代码

    这篇文章主要给大家介绍了关于java实现一致性hash算法的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-12-12
  • SpringBoot自定义注解API数据加密和签名校验

    SpringBoot自定义注解API数据加密和签名校验

    这篇文章主要介绍了SpringBoot自定义注解API数据加密和签名校验,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-04-04
  • OpenFeign超时时间设置不生效问题排查记录

    OpenFeign超时时间设置不生效问题排查记录

    文章主要讲述了在升级Spring Boot 3后,发现配置文件中的OpenFeign超时时间设置不生效的问题,通过查看FeignClientFactoryBean类和FeignClientProperties类的源码,发现配置读取的方式发生了变化,从而导致超时时间设置不生效
    2024-11-11
  • 深入学习springboot线程池的使用和扩展

    深入学习springboot线程池的使用和扩展

    这篇文章主要介绍了深入学习springboot线程池的使用和扩展,springboot框架提供了@Async注解,帮助我们更方便的将业务逻辑提交到线程池中异步执行,需要的朋友可以参考下
    2019-06-06
  • JAVA中Collections.sort()方法使用详解

    JAVA中Collections.sort()方法使用详解

    这篇文章主要给大家介绍了关于JAVA中Collections.sort()方法使用的相关资料,Java中Collections.sort()方法是用来对List类型进行排序的,文中通过代码将使用的方法介绍的非常详细,需要的朋友可以参考下
    2024-05-05
  • Java编程实现暴力破解WIFI密码的方法分析

    Java编程实现暴力破解WIFI密码的方法分析

    这篇文章主要介绍了Java编程实现暴力破解WIFI密码的方法,结合具体实例形式分析了java暴力破解WiFi密码的原理、操作步骤、实现技巧与相关注意事项,需要的朋友可以参考下
    2018-12-12
  • Java中Static关键字的五种用法详解

    Java中Static关键字的五种用法详解

    这篇文章主要介绍了Java中static的五种用法:修饰成员变量,修饰成员方法,修饰内部类,静态代码块,静态导包,想详细了解的小伙伴可以参考阅读本文
    2023-03-03
  • logback如何去掉DubboMonitor烦人的INFO日志

    logback如何去掉DubboMonitor烦人的INFO日志

    这篇文章主要介绍了logback如何去掉DubboMonitor烦人的INFO日志方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-07-07
  • Jpa中自定义枚举映射方式

    Jpa中自定义枚举映射方式

    本文介绍了JPA中枚举映射的方式,默认可用@Enumerated注解实现按名称或序号映射;若需按枚举属性自定义映射,则可用@Convert注解结合枚举转换器灵活实现
    2025-10-10
  • 移动指定文件夹内的全部文件

    移动指定文件夹内的全部文件

    移动指定文件夹内的全部文件
    2009-01-01

最新评论