cd /news/ai-tools/context-aware-spring-ai-chat-microse… · home topics ai-tools article
[ARTICLE · art-128513] src=dev.to ↗ pub= topic=ai-tools verified=true sentiment=· neutral

Context aware Spring AI chat microservice

A developer demonstrated how to build a context-aware Spring Boot chat microservice that connects to Google's Gemini API using Spring AI's ChatMemory Advisor to maintain conversation history. The implementation persists chat sessions across application restarts by backing the memory with a file-based H2 database via JdbcChatMemoryRepository, keyed to unique user sessions.

by read3 min views2 publishedSep 13, 2026

By default, Large Language Models (LLMs) are completely stateless. Every API call you make to Google Gemini is treated like a first-time introduction. If a user says "My name is Alex" in request one, and "What is my name?" in request two, Gemini will not know the answer.

To build a true chatbot experience, your microservice needs to remember the conversation history.

In this post, we will build a Spring Boot microservice that connects to the Gemini API, uses Spring AI's ChatMemory Advisor to maintain context, and backs up that history using a persistent H2 database mapped to unique user sessions.

The Architecture

Add the required dependencies to your pom.xml. This includes the Spring AI starter for Gemini, the chat memory module, and the H2 database driver.

<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-h2console</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-starter-model-chat-memory</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-starter-model-chat-memory-repository-jdbc</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-starter-model-google-genai</artifactId>
</dependency>

Configure Properties: Update the application.properties with chat model and get your API key from Google AI Studio

spring.ai.model.chat=google-genai
spring.ai.google.genai.api-key=API-KEY-GOES-HERE
spring.ai.google.genai.chat.model=gemini-3.5-flash

Instead of losing chat history on application restarts (which happens with default in-memory arrays), we configure a persistent ChatMemory bean backed by H2 using the JdbcChatMemoryRepository.

import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.memory.MessageWindowChatMemory;
import org.springframework.ai.chat.memory.repository.jdbc.H2ChatMemoryRepositoryDialect;
import org.springframework.ai.chat.memory.repository.jdbc.JdbcChatMemoryRepository;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;

@Configuration
public class ChatConfig {

    @Bean
    public JdbcChatMemoryRepository chatMemoryRepository(JdbcTemplate jdbcTemplate) {
        // Enforces H2 syntax quirks for database execution
        return JdbcChatMemoryRepository.builder().jdbcTemplate(jdbcTemplate)
                .dialect(new H2ChatMemoryRepositoryDialect())
                .build();
    }

    @Bean
    public ChatMemory chatMemory(JdbcChatMemoryRepository repository) {
        return MessageWindowChatMemory.builder()
                .chatMemoryRepository(repository).build();
    }

}

Configure properties: include the below in application.properties to maintain the session across application restarts and to enable h2-console

spring.datasource.url=jdbc:h2:file:~/data/demochat;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password

spring.h2.console.enabled=true
spring.h2.console.path=/h2-console

spring.ai.chat.memory.repository.jdbc.initialize-schema=always

We build the ChatClient and attach the MessageChatMemoryAdvisor. This advisor acts as an interceptor: it fetches past messages from H2 before sending the prompt to Gemini, and saves Gemini's response right after.

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.stereotype.Service;

@Service
public class ChatService {
    private final ChatClient chatClient;

    public ChatService(ChatClient.Builder chatClientBuilder, ChatMemory chatMemory){
        this.chatClient = chatClientBuilder.defaultAdvisors(MessageChatMemoryAdvisor.builder(chatMemory).build())
                .build();
    }

    public String getResponse(String sessionId, String queryString){
        return this.chatClient.prompt(queryString)
                .advisors(x -> x.param(ChatMemory.CONVERSATION_ID, sessionId))
                .call().content();
    }
}

Finally, we expose a POST endpoint. We use @RequestHeader("x-session-id") to extract the unique tracking key provided by the client application.

import ai.chat_bot.gemini.demo.service.ChatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api")
public class ChatController {
    @Autowired
    private ChatService chatService;

    @PostMapping("/ai/prompt")
    public String chat(@RequestHeader("x-session-id") String sessionId, @RequestBody String query){
        return chatService.getResponse(sessionId, query);
    }
}

You can test the context awareness using curl or Postman.

Request establishing a context:

curl --location --request POST 'http://localhost:8080/api/ai/prompt' \
--header 'x-session-id: 8757788243' \
--header 'Content-Type: application/json' \
--data-raw '{
    "query": "I love mangoes"
}'

Response: Mangoes are absolutely elite! There is a very good reason they are called the "King of Fruits." There is nothing quite like a perfectly ripe, juicy, sweet mango.

Request to verify history recall

curl --location --request POST 'http://localhost:8080/api/ai/prompt' \
--header 'x-session-id: 8757788243' \
--header 'Content-Type: application/json' \
--data-raw '{
    "query": "what do you think is my favorite fruit"
}'

Response: I’m going to go out on a limb here and make a wild guess... mangoes? 🥭 😉 Call it a hunch, but you seemed pretty enthusiastic about them a moment ago!

If you send the second request with a different session-id value, Gemini will correctly respond that it doesn't know and can give a generic response proving that multi-user session isolation is fully working.

By combining Spring AI's Advisor API with an H2 JDBC store, you can turn a stateless LLM endpoint into a fully stateful, context-aware chatbot microservice with minimal boilerplate code.

You can view the source code directly in my GitHub Repository

── more in #ai-tools 4 stories · sorted by recency
── more on @spring ai 3 stories trending now
sponsored brought to you by zahid.host 4,200+ EU-deployed projects
reading about agents? ship yours in a single git push.

Run your AI side-project on zahid.host

EU-based hosting, git-push deploys, automatic HTTPS, no cold starts. Free tier with a custom domain — perfect for shipping the agent you just read about.

$git push zahid main
Live at https://your-agent.zahid.host
Get free account → Pricing
from €0/mo · no card required
LIVE [news/context-aware-spring…] indexed:0 read:3min 2026-09-13 ·