GENERATIVE AI & SPRING#07 • Spring AI Architecture

Java + GenAI: The Complete Guide to Spring AI for Java Developers.

Java has seen many waves, but Generative AI is a major shift in enterprise software. Here is how Spring AI brings familiar POJO principles, portable Model APIs, Vector Stores, Tool Calling, and RAG into modern Java enterprise backends.

By Shyam KumarAug 28, 202610 min readSpring AI Architecture
#SpringAI#Java#GenAI#RAG
Enterprise Context

Integrating Generative AI into Enterprise Java Backends

Python is commonly used for early AI experiments and model training. But when AI needs to integrate into production business systems—connecting to PostgreSQL, consuming Kafka streams, respecting Spring Security, and running within transactional boundaries—Java is where enterprise software runs. Spring AI provides Spring-based APIs for integrating AI models into Java applications.

01 / OVERVIEW

Why GenAI Matters for Java Developers

Spring AI is an open-source framework by the Spring team that simplifies building AI-powered applications in Java.

Its core philosophy is to bring established Spring principles into the AI era:

Portability

Switch between OpenAI, Azure, Anthropic, Google Gemini, and local Ollama without modifying business logic.

Modular Design

Pluggable components for Vector Databases, Document Readers, Advisors, and Function Callers.

POJOs & Records

AI prompts and structured responses map directly to type-safe Java records and classes without manual JSON manipulation.

Spring AI Architecture Pipeline
Your Application
Your Database & Data
Your REST & Internal APIs
Spring AI Framework

Translates Enterprise Data ⇄ AI Prompts, Functions & Vector Embeddings

⇄ Two-Way Flow ⇄
Generative AI Layer
LLMs (OpenAI, Claude, Gemini)
Local Models (Ollama, vLLM)
02 / CORE CAPABILITIES

Features of Spring AI

Spring AI provides a structured, enterprise-ready approach to AI integration:

Major AI Providers Supported

OpenAI, Anthropic Claude, Azure OpenAI, AWS Bedrock, Google Vertex AI / Gemini, Mistral, and local Ollama.

Multiple Model Modalities

Chat, Embeddings, Text-to-Image (DALL-E), Audio Transcription (Whisper), Text-to-Speech (TTS), and Moderation.

Structured Output Mapping

Spring AI can map structured model responses to Java types and records without manual JSON parsing.

14+ Vector Stores Supported

PGVector (PostgreSQL), Pinecone, Redis, MongoDB Atlas, Cassandra, Milvus, Qdrant, Chroma, Neo4j, and more.

SQL-Like Vector Filtering

Write consistent metadata filters across vector databases using simple text expressions.

Native Tool / Function Calling

Allow LLMs to trigger your Spring Beans, database queries, and external APIs dynamically using standard Java methods.

ETL Ingestion for RAG

Read PDFs, DOCX, JSON, split into token chunks, compute embeddings, and store them into Vector DBs automatically.

Enterprise Observability

Built-in Micrometer metrics and OpenTelemetry tracing for token consumption, latency, and prompt auditing.

03 / MODEL ABSTRACTION

Portable AI Model API Architecture

Spring AI abstracts away proprietary vendor SDKs behind generic interfaces. Instead of calling OpenAI or Bedrock SDKs directly, you code to the generic Model<TReq, TResp> interface:

Model<TRequest, TResponse>
+ call(Req): Resp
ChatModelLLM Text & Conversations
EmbeddingModelFloat Arrays / Vectors
ImageModelDALL-E & Diffusion
SpeechModelWhisper & TTS Audio
StreamingModel<TRequest, TChunk>
+ stream(Req): Flux<Chunk>
StreamingChatModelReal-time token streaming via SSE
StreamingSpeechModelReal-time audio streaming
StreamingController.java(Java)
@RestController
@RequestMapping("/api/ai")
public class AiStreamingController {

    private final ChatClient chatClient;

    public AiStreamingController(ChatClient.Builder chatClientBuilder) {
        this.chatClient = chatClientBuilder.build();
    }

    // Stream tokens in real-time as Server-Sent Events (SSE)
    @GetMapping(value = "/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> streamAiResponse(@RequestParam String prompt) {
        return chatClient.prompt()
                .user(prompt)
                .stream()
                .content();
    }
}
04 / RETRIEVAL AUGMENTED GENERATION

Vector Store API & Retrieval Augmented Generation (RAG)

How Vector Databases Work

Traditional databases match exact keywords (WHERE name = 'John'). Vector databases store data as numerical embeddings (arrays of floating-point numbers representing semantic meaning). Instead of exact matches, they return results that are semantically similar to your query.

The 3-Step RAG Pipeline:

  1. Ingest & Embed: Internal documents (PDFs, knowledge base, policies) are broken into chunks, passed through EmbeddingModel, and stored in a VectorStore.
  2. Retrieve Context: When a user asks a question, Spring AI queries the VectorStore for the top 3-5 most similar chunks.
  3. Augment & Generate: The retrieved chunks are injected into the prompt as factual context before sending to the LLM. The LLM answers using the retrieved context.
RagService.java(Java)
@Service
public class DocumentRagService {

    private final ChatClient chatClient;
    private final VectorStore vectorStore;

    public DocumentRagService(ChatClient.Builder builder, VectorStore vectorStore) {
        this.chatClient = builder.build();
        this.vectorStore = vectorStore;
    }

    public String askCompanyPolicy(String userQuestion) {
        // Step 1: Search top 3 similar documents from PGVector with metadata filter
        List<Document> similarDocuments = vectorStore.similaritySearch(
            SearchRequest.query(userQuestion)
                .withTopK(3)
                .withSimilarityThreshold(0.75)
        );

        String context = similarDocuments.stream()
            .map(Document::getContent)
            .collect(Collectors.joining("\n---\n"));

        // Step 2: Pass retrieved context to LLM
        return chatClient.prompt()
            .system("You are an HR assistant. Answer strictly using only the provided context.")
            .user(u -> u.text("Context:\n{context}\n\nQuestion: {question}")
                        .param("context", context)
                        .param("question", userQuestion))
            .call()
            .content();
    }
}
05 / FUNCTION CALLING

Tool Calling API: Connecting LLMs to Application Code

LLMs by themselves are isolated text models—they do not have direct access to live databases, internal systems, or external APIs.Tool Calling allows the model to request method execution in your Java application.

The 6-Step Tool Calling Lifecycle:
1Application sends User Prompt + Tool Definitions (name, description, parameter schema) to AI Model.
2AI Model analyzes prompt and recognizes it needs real data. It responds with a Tool Call Request (JSON args).
3Spring AI intercepts the response and dispatches the execution to your local Java method.
4Java method executes (e.g. queries DB, calls third-party weather API) and returns raw data.
5Spring AI sends tool execution output back to the AI Model.
6AI Model consumes the tool output and returns the final natural language answer to the user.
WeatherToolConfig.java(Java)
@Configuration
public class ToolConfiguration {

    public record WeatherRequest(String city) {}
    public record WeatherResponse(String city, double tempC, String condition) {}

    // Expose a standard Java java.util.Function as an AI Tool
    @Bean
    @Description("Get current live weather temperature and condition for a given city")
    public Function<WeatherRequest, WeatherResponse> currentWeatherFunction() {
        return request -> {
            // Live API or Database call
            return new WeatherResponse(request.city(), 28.5, "Partly Cloudy");
        };
    }
}

// In your service:
public String askWithTools(String question) {
    return chatClient.prompt()
        .user(question)
        .functions("currentWeatherFunction") // Activated!
        .call()
        .content();
}
06 / CHATCLIENT & ADVISORS

ChatClient API & Advisors API

ChatClient API (Fluent Builder)

Similar to Spring's WebClient or RestClient. It provides a clean, chainable fluent builder for prompts, system instructions, temperature, output entity mapping, and streaming.

Advisors API (Aspect-Oriented GenAI)

Lets you intercept AI calls like Spring AOP. You can automatically inject conversation history (chat memory), apply safe guardrails, log token counts, or inject RAG vectors into every call without repeating boilerplate.

ChatClientWithAdvisors.java(Java)
@Service
public class CustomerSupportBot {

    private final ChatClient chatClient;

    public CustomerSupportBot(ChatClient.Builder builder, VectorStore vectorStore) {
        this.chatClient = builder
            // Advisor 1: Keep last 10 messages of conversation in memory per session
            .defaultAdvisors(
                new MessageChatMemoryAdvisor(new InMemoryChatMemory()),
                // Advisor 2: Automatically attach relevant RAG vectors
                new QuestionAnswerAdvisor(vectorStore, SearchRequest.defaults())
            )
            .build();
    }

    public String chatWithUser(String conversationId, String message) {
        return chatClient.prompt()
            .advisors(a -> a.param(AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY, conversationId))
            .user(message)
            .call()
            .content();
    }
}
07 / PRACTICAL PROJECTS

10 Project Ideas to Build With Spring AI

Here are 10 production-inspired project ideas you can build with Spring Boot 3 and Spring AI:

01. Voice-to-Text Notes App

Upload audio files, transcribe using Whisper SpeechModel, and summarize key action items.

02. AI-Based Code Snippet Generator

Takes natural language descriptions and returns structured Spring Boot Controller and Service classes.

03. AI Email Classification System

Classifies incoming emails into Spam, Urgent, Billing, or Inquiry using structured POJO output.

04. AI-Powered Chat Support System

Multi-turn customer support bot with session-based memory using MessageChatMemoryAdvisor.

05. Smart Document Q&A Service (RAG)

Ingests internal PDFs into PostgreSQL PGVector and answers enterprise queries using the retrieved context.

06. AI-Based SQL Query Generator

Converts plain English queries into safe, read-only SQL queries validated against your schema.

07. Code Review Assistant for Java

Analyzes Java pull request diffs for concurrency bugs, SQL injection, and missing unit tests.

08. Email Summarizer & Smart Reply

Summarizes 20+ thread email chains and suggests 3 professional one-click responses.

09. Weather Query Assistant (Tool Calling)

Demonstrates dynamic tool invocation where the LLM fetches live external weather data from an external service.

10. AI-Powered Interview Generator

Uploads a candidate's resume and generates tailored Spring Boot architectural interview scenarios.

08 / SUMMARY & ROADMAP

A Practical Roadmap for Java Developers

For Java developers, this is the right time to start experimenting with Spring AI. Building small, practical prototypes helps clarify how LLMs, vector search, and tool execution operate in production.

Spring provides clean abstractions, stable APIs, and a familiar ecosystem.

Official Spring AI Documentation:
spring.io/projects/spring-ai

Did you find this Spring AI breakdown helpful?

Share it with fellow backend engineers integrating Generative AI into modern enterprise Java applications!

Like: If you appreciate clean Java AI engineering
Share: With your backend and cloud teams
Back to All Articles in The Tech Corner
Discuss GenAI Architecture? Contact Me