Spring Boot auto-configuration for chat memory functionality in Spring AI applications
This guide walks you through setting up and using Spring AI Chat Memory in your application.
Add the Spring AI Chat Memory auto-configuration dependency to your project.
Maven:
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-autoconfigure-model-chat-memory</artifactId>
<version>1.1.2</version>
</dependency>Gradle:
implementation 'org.springframework.ai:spring-ai-autoconfigure-model-chat-memory:1.1.2'Spring Boot automatically creates the necessary beans. Simply inject and use them:
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.messages.AssistantMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class ConversationService {
@Autowired
private ChatMemory chatMemory;
public void addUserMessage(String conversationId, String content) {
chatMemory.add(conversationId, new UserMessage(content));
}
public void addAssistantMessage(String conversationId, String content) {
chatMemory.add(conversationId, new AssistantMessage(content));
}
public List<Message> getConversationHistory(String conversationId) {
return chatMemory.get(conversationId);
}
public void clearConversation(String conversationId) {
chatMemory.clear(conversationId);
}
}// Add a user message
chatMemory.add("conversation-123", new UserMessage("What is Spring AI?"));
// Add an assistant response
chatMemory.add("conversation-123", new AssistantMessage("Spring AI is..."));
// Add a system instruction
chatMemory.add("conversation-123", new SystemMessage("You are a helpful assistant."));// Get all messages for a conversation
List<Message> messages = chatMemory.get("conversation-123");
// Process messages
for (Message message : messages) {
System.out.println(message.getMessageType() + ": " + message.getText());
}// Remove all messages for a conversation
chatMemory.clear("conversation-123");System messages provide context and instructions to the AI model:
@Service
public class ConversationInitializer {
@Autowired
private ChatMemory chatMemory;
public void initializeConversation(String conversationId) {
SystemMessage systemMessage = new SystemMessage(
"You are a helpful coding assistant specializing in Spring Framework."
);
chatMemory.add(conversationId, systemMessage);
}
}Key Behavior: System messages are preserved when the message window fills up, and new system messages replace old ones.
Each conversation has a unique ID. Use meaningful IDs to organize conversations:
@Service
public class MultiUserChatService {
@Autowired
private ChatMemory chatMemory;
public void handleUserMessage(String userId, String message) {
String conversationId = "user:" + userId;
chatMemory.add(conversationId, new UserMessage(message));
// Process with AI...
String response = processWithAI(conversationId);
chatMemory.add(conversationId, new AssistantMessage(response));
}
private String processWithAI(String conversationId) {
List<Message> history = chatMemory.get(conversationId);
// Use history to provide context to AI model
return "AI response based on history";
}
}By default, only the last 20 messages are kept. To change this:
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.memory.ChatMemoryRepository;
import org.springframework.ai.chat.memory.MessageWindowChatMemory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ChatMemoryConfiguration {
@Bean
public ChatMemory chatMemory(ChatMemoryRepository chatMemoryRepository) {
return MessageWindowChatMemory.builder()
.chatMemoryRepository(chatMemoryRepository)
.maxMessages(100) // Keep last 100 messages
.build();
}
}The default in-memory repository loses data on restart. For production, use a persistent repository:
JDBC Example:
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-autoconfigure-model-chat-memory-repository-jdbc</artifactId>
<version>1.1.2</version>
</dependency># application.properties
spring.ai.chat.memory.repository.jdbc.initialize-schema=always
spring.ai.chat.memory.repository.jdbc.platform=postgresqlMongoDB Example:
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-autoconfigure-model-chat-memory-repository-mongodb</artifactId>
<version>1.1.2</version>
</dependency># application.properties
spring.ai.chat.memory.repository.mongo.create-indices=true
spring.ai.chat.memory.repository.mongo.ttl=PT24Hpublic void startConversationWithContext(String conversationId, String userRole) {
// Set system context
chatMemory.add(conversationId, new SystemMessage(
"You are assisting a " + userRole + " with technical questions."
));
// Add initial message
chatMemory.add(conversationId, new UserMessage("Hello!"));
}public void addMessagesBatch(String conversationId, List<Message> messages) {
// More efficient than multiple single adds
chatMemory.add(conversationId, messages);
}public boolean addMessageSafely(String conversationId, Message message) {
try {
if (conversationId == null || conversationId.trim().isEmpty()) {
logger.error("Invalid conversation ID");
return false;
}
if (message == null) {
logger.error("Message cannot be null");
return false;
}
chatMemory.add(conversationId, message);
return true;
} catch (IllegalArgumentException e) {
logger.error("Validation error: {}", e.getMessage());
return false;
}
}Problem: Messages disappear after application restart.
Solution: You're using the default in-memory repository. Add a persistent repository dependency (JDBC, MongoDB, etc.).
Problem: Older messages disappear before you expect.
Solution: Increase the maxMessages setting when creating your ChatMemory bean.
Problem: Getting exceptions when adding messages.
Solution: Ensure conversationId is not null/empty and message is not null. Add validation before calling ChatMemory methods.
You've learned how to:
For more advanced usage, see the Real-World Scenarios and API Reference.
tessl i tessl/maven-org-springframework-ai--spring-ai-autoconfigure-model-chat-memory@1.1.0