Albaraa Ahmed/ Writing
Portfolio
SpringAISpringBootJava

Spring AI in Practice: Chat, Streaming, Tools and Structured Output with Claude.

Dec 1, 20264 min read

If you write Java with Spring, adding an LLM to your app used to mean hand-writing HTTP calls to a provider's API, parsing JSON responses, and wiring up streaming yourself. Spring AI turns all of that into something that feels like the rest of Spring: a starter dependency, a few properties, and a client you inject.

To learn it properly, I built a small demo: one controller, one class of tools, and four endpoints that each show one core feature. The whole thing is under 50 lines of actual Java. This post walks through it.

Stack: Java 21, Spring Boot 4.2, Spring AI 2.1, and Anthropic's Claude (claude-sonnet-5-5).

Code: github.com/baarayy/spring-ai-demo

#FeatureEndpoint
1Simple chatGET /chat
2StreamingGET /chat/stream
3Tool callingGET /chat/tools
4Structured outputGET /movies

The setup: one dependency, three properties

Everything comes from a single starter. Its version is managed by the Spring AI BOM:

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

Configuration lives where you'd expect it, in application.properties:

properties
# Read from the environment - never hard-code the key
spring.ai.anthropic.api-key=${ANTHROPIC_API_KEY}
spring.ai.anthropic.chat.options.model=claude-sonnet-5-5
spring.ai.anthropic.chat.options.max-tokens=1024

That's it. No HTTP client, no request DTOs, no JSON mapping.

ChatClient: one API, four endings

Spring AI auto-configures a ChatClient.Builder that's already connected to Claude. You inject it like any other bean and build a client, optionally with a system prompt that applies to every request:

java
@RestController
public class ChatController {

    private final ChatClient chatClient;

    public ChatController(ChatClient.Builder builder) {
        this.chatClient = builder
                .defaultSystem("You are a friendly, concise assistant.")
                .build();
    }
}

What I like most about this API is that every feature is the same fluent chain with a different ending:

java
chatClient.prompt().user(message).call().content();               // 1. full text
chatClient.prompt().user(message).stream().content();             // 2. Flux<String> of tokens
chatClient.prompt().user(message).tools(new DemoTools())
          .call().content();                                      // 3. with tools
chatClient.prompt().user("...").call().entity(MovieList.class);   // 4. mapped to a record

Once you've learned the first one, you've basically learned all four.

1. Simple chat

Send a message, get the whole answer back as a String:

java
@GetMapping("/chat")
public String chat(@RequestParam(defaultValue = "Tell me a fun fact about Java.") String message) {
    return chatClient.prompt().user(message).call().content();
}
bash
curl -G http://localhost:8080/chat --data-urlencode "message=Explain dependency injection in two sentences"

2. Streaming

For anything longer than a sentence, users don't want to stare at a spinner. Swap .call() for .stream() and you get a Flux<String>. Return it with the text/event-stream media type and each chunk goes to the client as a Server-Sent Event while Claude is still writing:

java
@GetMapping(value = "/chat/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<String> stream(@RequestParam(defaultValue = "Write a haiku about Spring.") String message) {
    return chatClient.prompt().user(message).stream().content();
}

Use -N so curl doesn't buffer the output, and you'll see the tokens arrive one by one:

bash
curl -N http://localhost:8080/chat/stream

3. Tool calling

This is the feature that makes an LLM useful inside a real application. A model can't know the current time, your database contents, or the result of a calculation it can't do reliably. With tool calling, it can ask your code.

In Spring AI, a tool is just a Java method with an annotation:

java
public class DemoTools {

    @Tool(description = "Get the current date and time in a given IANA time zone, e.g. Asia/Tokyo")
    public String currentTime(@ToolParam(description = "IANA time zone id, e.g. Europe/Paris") String timeZone) {
        return ZonedDateTime.now(ZoneId.of(timeZone)).toString();
    }

    @Tool(description = "Add two numbers exactly")
    public double add(double a, double b) {
        return a + b;
    }
}

And you pass the tools to the request:

java
@GetMapping("/chat/tools")
public String tools(@RequestParam(defaultValue = "What time is it in Tokyo right now?") String message) {
    return chatClient.prompt().user(message).tools(new DemoTools()).call().content();
}

Here's what happens behind that one line:

  1. Spring AI sends each method's name, description and parameter schema to Claude along with your prompt.
  2. Claude decides it needs a tool and replies with a tool call, for example currentTime("Asia/Tokyo").
  3. Spring AI runs your Java method and sends the result back to Claude.
  4. Claude writes its final answer using that result.

You don't write any of that loop. You write the method.

The lesson: the description strings are the only information the model has for deciding when and how to call your tool. Treat them like API documentation for a reader who can't see your code.

4. Structured output

Most of the time you don't want prose back; you want data your code can use. Define a record and ask for it with .entity(...):

java
public record Movie(String title, int year, String oneLineSummary) {}
public record MovieList(String director, List<Movie> movies) {}

@GetMapping("/movies")
public MovieList movies(@RequestParam(defaultValue = "Christopher Nolan") String director) {
    return chatClient.prompt()
            .user("List 3 well-known movies directed by " + director + ".")
            .call()
            .entity(MovieList.class);
}

Spring AI turns the record into a JSON schema, adds format instructions to the prompt, and parses Claude's reply back into a MovieList. Spring MVC then serializes it to JSON like any other return value:

json
{
  "director": "Christopher Nolan",
  "movies": [
    { "title": "Inception", "year": 2010, "oneLineSummary": "A thief steals secrets by entering people's dreams." }
  ]
}

What I took away from it

  • It feels like Spring. Auto-configuration, application.properties, constructor injection. There was very little new to learn beyond the ChatClient chain itself.
  • Your code isn't tied to one provider. To switch from Claude to OpenAI or a local model with Ollama, you replace the starter (spring-ai-starter-model-openai or spring-ai-starter-model-ollama) and the config. The ChatClient code stays the same.
  • Tool descriptions are prompts. Vague descriptions mean the model calls the wrong tool, or none. This is where most of the "prompt engineering" in a tool-using app actually happens.
  • Keep the API key out of the code. The key comes from ANTHROPIC_API_KEY, and the tests run with a dummy key, so CI never needs a real one or makes paid calls.
  • Mind your costs. Every call is billed by tokens. max-tokens is a cheap safety net, and you can switch to a smaller, faster model (like claude-haiku-5-5) for a single run without editing anything:
bash
./mvnw spring-boot:run -Dspring-boot.run.arguments=--spring.ai.anthropic.chat.options.model=claude-haiku-5-5

Try it yourself

You need JDK 21+ and an Anthropic API key. The Maven wrapper is included, so you don't need Maven installed.

bash
git clone https://github.com/baarayy/spring-ai-demo
cd spring-ai-demo
export ANTHROPIC_API_KEY=sk-ant-...
./mvnw spring-boot:run

Then open http://localhost:8080/chat in your browser, or try:

bash
curl -G http://localhost:8080/chat/tools --data-urlencode "message=What is 123456.78 plus 987654.32, and what time is it in Paris?"
curl -G http://localhost:8080/movies --data-urlencode "director=Greta Gerwig"

What's next

This demo covers the basics. Next I want to explore:

  • Chat memory with MessageChatMemoryAdvisor, so a conversation can span multiple requests.
  • RAG (Retrieval-Augmented Generation) with a VectorStore and QuestionAnswerAdvisor, so the model can answer questions from my own documents.

If you've used Spring AI in production, I'd love to hear what worked and what surprised you.


Source code: github.com/baarayy/spring-ai-demo · Spring AI docs: docs.spring.io/spring-ai/reference

Keep reading