1. ChatMemory 的配置
SpringAI 基于 ChatMemory 实现对话的'记忆',也就是上下文内容的存储、发送请求时候附带。
ChatMemory 表示聊天对话记忆的存储,它提供添加消息到对话、从对话中检索消息以及清除对话历史的方法。目前有一个内置实现:MessageWindowChatMemory,它维护一个最多可达到指定最大大小的消息窗口(默认 20 条消息),当消息数量超过这个限制时,较旧的消息会被移除。Spring AI 提供了 ChatMemoryRepository 的实例用于存储聊天上下文,默认使用 InMemoryChatMemoryRepository 类型实现,将对话直接存储在内存中。
新建一个配置类,用来配置 ChatMemory(不想配置也可以直接注入使用,跳过本段):
package com.demo.aiqqq.config;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.memory.InMemoryChatMemoryRepository;
import org.springframework.ai.chat.memory.MessageWindowChatMemory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MemConfig {
/**
* ChatMemory 聊天对话记忆的存储
*/
@Bean
public ChatMemory chatMemory() {
// 当前版本的 MessageWindowChatMemory 是 ChatMemory 的唯一默认实现类
// 并且构造器已经私有化,只提供 Builder 模式来创建实例;这点与之前的版本不一样
return MessageWindowChatMemory.builder()
// 对话存储的 repository 存储库层的实现方式,如果不配置,默认也是 Spring 提供的 InMemoryChatMemoryRepository
.chatMemoryRepository(new InMemoryChatMemoryRepository())
// 有默认 maxMessages(20)
// 最大消息数
.maxMessages(20)
.build();
}
}
MessageWindowChatMemory 的实例同样只能通过 builder() 获取,并且需要添加 ChatMemoryRepository 实现(本例中所有实例化的 bean 都在 SpringAI 有默认实现,可以直接注入)。
详细资料可参考:Chat Memory :: Spring AI Reference。
ChatMemoryRepository 的其他实现(持久化存储)可参考官方文档中的 JDBCChatMemoryRepository。
ChatMemory 甚至可以不用手动配置该类,直接注入使用即可(SpringAI 有封装默认实现)。


