Spring AI: Adding LLM Features to Spring Boot Services

How the Spring AI project lets Java teams add large language model features to Spring Boot services using ChatClient, prompt templates, structured output, tests and fallbacks.

Many Indian companies run their core systems on Java and Spring Boot: order management, lending platforms, HR systems, internal portals. When the business asks for an AI feature, such as summarising customer complaints, drafting replies or extracting fields from a document, the first instinct is often to build a separate Python service. That can be the right choice, but it also adds a new deployment, a new language and a new set of operational concerns.

The Spring AI project offers another route. It brings large language model (LLM) integration into the Spring ecosystem with familiar patterns: auto-configuration, dependency injection and properties files. This article walks through the main ideas and how to use them responsibly. Spring AI is evolving quickly, so treat the code here as an illustration of the concepts and check the official documentation for the exact API of the version you use.

What Spring AI provides

Spring AI is a Spring project that gives a common abstraction over several AI providers, including hosted LLM APIs and locally run models. Its main building blocks are:

  • Chat models for sending prompts and receiving responses, with provider-specific starters.
  • ChatClient, a fluent API on top of the chat model that most application code uses.
  • Prompt templates for building prompts with placeholders instead of string concatenation.
  • Structured output to convert model responses into Java objects.
  • Embedding models and vector store integrations for retrieval-augmented generation (RAG), where the model answers using your own documents.

The value of the abstraction is that your business code depends on Spring AI interfaces rather than a particular vendor SDK. Switching providers, or running a local model in development and a hosted one in production, becomes largely a configuration change.

Configuration through application properties

You add the starter for your chosen provider to the build, and Spring Boot auto-configures the chat model and a ChatClient.Builder bean. Provider settings live in application.properties or application.yml. For an OpenAI-compatible setup, it looks roughly like this:

spring.ai.openai.api-key=${OPENAI_API_KEY}
spring.ai.openai.chat.options.model=your-model-name
spring.ai.openai.chat.options.temperature=0.2

A few practical points:

  • Never commit API keys. Read them from environment variables or a secrets manager, as above.
  • Use profiles to point development at a cheaper or local model and production at the model you have tested.
  • Keep temperature low for tasks such as extraction and classification where you want consistent output.

Calling the model with ChatClient

The usual pattern is to inject ChatClient.Builder, build a client once (optionally with a default system prompt) and call it from a service. Here is a service that summarises a customer complaint:

@Service
public class ComplaintSummaryService {

    private final ChatClient chatClient;

    public ComplaintSummaryService(ChatClient.Builder builder) {
        this.chatClient = builder
                .defaultSystem("You summarise customer complaints for a support team. "
                        + "Be factual and brief. Do not invent details.")
                .build();
    }

    public String summarise(String complaintText) {
        return chatClient.prompt()
                .user(complaintText)
                .call()
                .content();
    }
}

This reads like any other Spring service. Controllers and other services call summarise() without knowing which provider sits behind it.

Prompt templates and structured output

Hard-coded strings become messy as prompts grow. Spring AI supports templates with named placeholders, so the prompt text can be kept in one place, reviewed and versioned like any other resource. The user specification accepts a template and parameters, along the lines of .user(u -> u.text("Classify this ticket: {ticket}").param("ticket", text)).

More useful still is structured output. Instead of parsing free text, you can ask Spring AI to map the response to a Java record. It adds format instructions to the prompt and converts the returned JSON:

public record TicketTriage(String category, String priority, String summary) {}

public TicketTriage triage(String ticketText) {
    return chatClient.prompt()
            .user(u -> u.text("Triage this support ticket. Category must be one of "
                    + "BILLING, DELIVERY, PRODUCT, OTHER. Priority is LOW, MEDIUM or HIGH.\n\n{ticket}")
                    .param("ticket", ticketText))
            .call()
            .entity(TicketTriage.class);
}

Treat the result as untrusted input. Models can return values outside your allowed list or leave fields empty, so validate the record (for example with Bean Validation or explicit checks) before saving it or acting on it.

Testing LLM-backed services

LLM output is not deterministic, which makes testing different from ordinary unit tests. A layered approach works well:

  • Isolate the AI call. Put model calls behind your own interface, such as TicketTriageClient. Business logic tests then use a simple fake that returns fixed records, with no network calls.
  • Test parsing and validation. Feed sample responses, including malformed ones, into your validation code and check that it rejects bad data.
  • Run evaluation sets separately. Keep a set of real, anonymised examples with expected outcomes and run them against the actual model before changing prompts or models. Track how many pass rather than expecting identical text.
  • Avoid real customer data in tests. Under the Digital Personal Data Protection Act, 2023, personal data should be used only for the purposes it was collected for; anonymise samples.

Fallbacks, timeouts and cost control

An LLM provider is an external dependency that can be slow, rate-limited or unavailable. Design for that from the start:

  • Set timeouts on the underlying HTTP client so a slow response does not tie up request threads.
  • Catch failures and degrade gracefully. If triage fails, route the ticket to a default queue rather than returning an error to the customer.
  • Consider a circuit breaker (for example with Resilience4j) so repeated failures stop hammering the provider.
  • Move long tasks off the request path. Batch summarisation or document processing belongs in a queue or scheduled job.
  • Log usage, not content. Record token counts, latency and errors for cost tracking, but be careful about logging prompts that contain personal data.

Above all, keep a human in the loop where a wrong answer has real consequences, such as credit decisions or medical information.

How NextWebGen can help

NextWebGen builds and maintains business applications, including Java and Spring Boot back ends. If you want to add summarisation, classification or document extraction to an existing system, we can help you design the integration, validation and fallbacks so the feature is dependable in production. Request a free quote to discuss your use case.