In part 3 we called an LLM with plain Java: build the JSON, send it with HttpClient, read the reply with Jackson, handle errors, retry, stream. It took about 80 lines, and we understood every one of them.
Now we let Spring do that work. Spring AI is the Spring team’s project for AI apps, and its main tool is ChatClient. Here is the whole call from part 3, the Spring AI way:
String answer = chatClient.prompt()
.user("Explain AI in two sentences.")
.call()
.content();
This is part 5 of Java for AI Engineers, and the first part of the Core frameworks module. We set up Spring AI with a local model, then go through the things you will use every day: prompts and templates, getting a Java record back, streaming, conversation memory, and switching between models.
What Spring AI is
Spring AI gives you one Java API for many AI providers (OpenAI, Anthropic, Google, Ollama and more) plus Spring Boot auto-configuration, so you add a dependency, set a few properties, and inject what you need. It also covers chat memory, tools, RAG and vector stores, which we use later in the series.
This article uses Spring AI 2.0. It reached general availability on 12 June 2026 and is built for Spring Boot 4.0 / 4.1 and Spring Framework 7. It doesn’t run on Spring Boot 3. Many tutorials online were written for Spring AI 1.x, and some names changed in 2.0. The last section lists the changes you are most likely to hit.
Setup: a Spring Boot app with a local model
We use Ollama with the qwen3.5:4b model, like in part 3, so you need no API key and pay nothing:
ollama pull qwen3.5:4b
Create a Spring Boot 4 project on start.spring.io with Java 21, and add the Spring Web and Ollama dependencies. Or add Spring AI to an existing Boot 4 project yourself: import the Spring AI BOM, then add the Ollama starter.
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-bom</artifactId>
<version>2.0.2</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-model-ollama</artifactId>
</dependency>
</dependencies>
(Use the newest 2.0.x version when you read this. The BOM keeps all Spring AI modules on the same version, so you never set versions on the starters.)
Then tell Spring AI where Ollama is and which model to use, in application.properties:
spring.ai.ollama.base-url=http://localhost:11434
spring.ai.ollama.chat.model=qwen3.5:4b
spring.ai.ollama.chat.temperature=0.2
That’s all the setup. When the app starts, the starter creates a ChatModel bean that talks to Ollama, and a ChatClient.Builder bean you can inject anywhere.
Your first ChatClient
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
class AskController {
private final ChatClient chatClient;
AskController(ChatClient.Builder builder) {
this.chatClient = builder.build();
}
@GetMapping("/ask")
String ask(@RequestParam String question) {
return chatClient.prompt()
.user(question)
.call()
.content();
}
}
Run the app and open http://localhost:8080/ask?question=What is Java?. You get the model’s answer as plain text.
Read the chain left to right, because almost everything in Spring AI follows this shape:
prompt()starts a new request.user(...)adds the user message. (There’s alsosystem(...)for instructions.)call()sends it and waits for the full answer.content()gives you the answer as aString.
Compare it with part 3. You didn’t build JSON, set headers, check status codes or parse the reply. Spring AI did all of that. It also comes with retries for temporary errors, which you can tune with the spring.ai.retry.* properties.
Defaults: a system message for every request
Most apps want the same instructions on every call: who the assistant is, how long answers should be, what it must not do. Set them once on the builder with defaultSystem:
AskController(ChatClient.Builder builder) {
this.chatClient = builder
.defaultSystem("""
You are a friendly Java teacher.
Answer in at most three sentences.
If you are not sure, say so.
""")
.build();
}
Now every prompt() from this client starts with that system message. You can still add a system(...) on a single request when one call needs different instructions.
Prompt templates: fill in the blanks
Real prompts mix fixed text with data. Instead of gluing strings together, use a template with {placeholders} and fill them with param:
String explain(String topic, String level) {
return chatClient.prompt()
.user(u -> u.text("Explain {topic} to a {level} Java developer, with one short example.")
.param("topic", topic)
.param("level", level))
.call()
.content();
}
explain("records", "beginner") sends “Explain records to a beginner Java developer, with one short example.”
When a prompt gets long, move it out of the code into a file under src/main/resources, and pass it in as a Resource:
@Value("classpath:/prompts/explain.st")
private Resource explainPrompt;
// ...
chatClient.prompt()
.user(u -> u.text(explainPrompt).param("topic", topic).param("level", level))
.call()
.content();
Now the prompt can be reviewed and changed like any other text file, without touching Java.
Get a Java object back with entity()
In part 4 we asked the model for JSON and read it into a record with Jackson. Spring AI does that in one step. End the chain with entity(...) instead of content():
record Invoice(String number, String customer, double total, List<String> items) {}
Invoice readInvoice(String emailText) {
return chatClient.prompt()
.user(u -> u.text("Read this email and pull out the invoice details:\n{email}")
.param("email", emailText))
.call()
.entity(Invoice.class);
}
Behind the scenes, Spring AI looks at your record, adds instructions to the prompt describing the JSON it expects, and turns the model’s answer into an Invoice. For a list, pass a type reference: .entity(new ParameterizedTypeReference<List<Invoice>>() {}).
The advice from part 4 still holds: the model can still get it wrong. Keep your checks in the record’s compact constructor, so a bad answer fails loudly. Spring AI 2.0 can also check the answer against the expected schema and ask the model again when it doesn’t match. The structured output page of the Spring AI docs shows how to turn that on.
Change settings for one request
The properties file sets the defaults. To change a setting for a single call, like a higher temperature for brainstorming, pass options to that request. In Spring AI 2.0 you pass the options builder, not a built object:
String names = chatClient.prompt()
.user("Suggest five fun names for a Java meetup group.")
.options(OllamaChatOptions.builder().temperature(0.9))
.call()
.content();
Each provider has its own options class (OllamaChatOptions, OpenAiChatOptions, AnthropicChatOptions and so on), because each has some settings the others don’t. Use them only where you really need a provider-specific setting. If you stick to the properties file, your code stays provider-neutral.
Stream the answer word by word
Swap call() for stream(), and you get a reactive Flux<String> that sends the words as the model writes them:
@GetMapping(value = "/ask/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
Flux<String> askStream(@RequestParam String question) {
return chatClient.prompt()
.user(question)
.stream()
.content();
}
Spring MVC can return a Flux like this one and sends each piece to the browser as a server-sent event. It’s the same data: lines we read by hand in part 3, only now Spring does the work on both sides.
Remember the conversation with an advisor
Part 2 explained that the model remembers nothing, so your app must send the history every time. Spring AI does this with an advisor: a piece of code that runs around every call and can change the request before it goes out and the response after it comes back.
MessageChatMemoryAdvisor adds the conversation history to each request and saves the new messages afterwards. Spring AI auto-configures a ChatMemory bean for you. By default it keeps the last 20 messages per conversation, in memory.
@RestController
class ChatController {
private final ChatClient chatClient;
ChatController(ChatClient.Builder builder, ChatMemory chatMemory) {
this.chatClient = builder
.defaultSystem("You are a friendly assistant. Keep answers short.")
.defaultAdvisors(MessageChatMemoryAdvisor.builder(chatMemory).build())
.build();
}
@GetMapping("/chat")
String chat(@RequestParam String conversationId, @RequestParam String message) {
return chatClient.prompt()
.user(message)
.advisors(a -> a.param(ChatMemory.CONVERSATION_ID, conversationId))
.call()
.content();
}
}
Try it:
/chat?conversationId=asha&message=My name is Asha/chat?conversationId=asha&message=What is my name?→ it knows: Asha./chat?conversationId=ravi&message=What is my name?→ it doesn’t. That’s a different conversation.
The conversation ID decides whose history is used. In a real app, use the logged-in user’s ID or a chat session ID. In Spring AI 2.0 it’s required: if you forget to pass it, the memory advisor throws an error instead of quietly mixing everyone’s messages into one shared “default” conversation.
Two things to know before you go to production:
- In-memory history is lost on restart, and it isn’t shared between app instances. Spring AI has repositories that store chat memory in a database (JDBC, Cassandra, Neo4j and others).
- 20 messages is a window, not a token budget. Long messages can still fill the context window. Keep the window small and the system message short.
Log what is really sent
When an answer looks wrong, the first question is always: what exactly did we send? Add SimpleLoggerAdvisor to log every request and response:
builder.defaultAdvisors(new SimpleLoggerAdvisor())
and turn its logging on:
logging.level.org.springframework.ai.chat.client.advisor=DEBUG
You’ll see the full prompt, including the system message and the history the memory advisor added. That is often where the bug is.
Switching models: the real benefit
Your controller code talks to ChatClient, and ChatClient talks to the ChatModel interface. It never names a provider. The starter you add decides which ChatModel you get.
To move from local Ollama to OpenAI, you change the build file and the properties, not the Java code. Replace the starter:
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-model-openai</artifactId>
</dependency>
and the properties:
spring.ai.openai.api-key=${OPENAI_API_KEY}
spring.ai.openai.chat.model=<a model name from OpenAI's docs>
Every controller above keeps working. The same goes for Anthropic, Google and the other providers Spring AI supports. This is useful in practice: develop and test against a free local model, then run a cloud model in production, or move to a cheaper provider later without a rewrite.
Need two models in one app, say a small cheap one for simple tasks and a bigger one for hard ones? Add both starters and build one ChatClient per model with ChatClient.builder(chatModel), injecting each ChatModel bean by name. The Spring AI docs describe the properties to control which models are auto-configured.
Coming from Spring AI 1.x?
If you follow an older tutorial, these 2.0 changes cause most of the confusion:
| In Spring AI 1.x | In Spring AI 2.0 |
|---|---|
| Runs on Spring Boot 3 | Needs Spring Boot 4.0 or 4.1 |
spring.ai.ollama.chat.options.model |
spring.ai.ollama.chat.model (the .options part is gone) |
.options(SomeOptions.builder()...build()) |
.options(SomeOptions.builder()...): pass the builder |
| A default conversation ID was used if you passed none | You must pass ChatMemory.CONVERSATION_ID |
PromptChatMemoryAdvisor |
Removed; use MessageChatMemoryAdvisor |
| Jackson 2 | Jackson 3 |
The official upgrade notes in the Spring AI docs list every change.
What Spring AI did for you
| In part 3 (plain Java) | With Spring AI |
|---|---|
| Records for the JSON request and response | Built in |
| Base URL, key and model from environment variables | application.properties |
| Check status codes, retry on 429 and 5xx | Built in, tunable with spring.ai.retry.* |
| Parse server-sent events for streaming | .stream().content() |
Keep a List<Message> per conversation |
MessageChatMemoryAdvisor |
| Read the model’s JSON into a record | .entity(MyRecord.class) |
| Rewrite the client for a new provider | Change the starter and properties |
You still need everything you learned in parts 1 to 4. Spring AI hides the HTTP call, not the behaviour of the model. Tokens, context windows, temperature and validation work exactly the same.
Key takeaways
- Spring AI 2.0 targets Spring Boot 4. Add the BOM and a model starter, set a few properties, and inject
ChatClient.Builder. chatClient.prompt().user(...).call().content()is the basic call.system(...)adds instructions;defaultSystemsets them for every call.- Use templates with
{placeholders}andparam(...), and keep long prompts in resource files. entity(MyRecord.class)turns the answer into a Java object. Keep validation in the record.stream().content()returns aFlux<String>for word-by-word answers.MessageChatMemoryAdvisorkeeps the history; always pass a conversation ID.- Your code depends on
ChatModel, not a provider. Switching models is a change of starter and properties.
Frequently asked questions
What is ChatClient in Spring AI?
ChatClient is Spring AI’s main API for talking to a chat model. You build a request with a fluent chain (prompt(), system(), user(), options(), advisors()), send it with call() or stream(), and read the answer as text, as a Java object, or as a stream.
What is the difference between ChatClient and ChatModel?
ChatModel is the low-level interface each provider implements: it takes a prompt and returns a response. ChatClient sits on top and adds the fluent API, defaults, templates, structured output and advisors such as chat memory. Use ChatClient in application code.
Does Spring AI work with Spring Boot 3?
Spring AI 1.x works with Spring Boot 3. Spring AI 2.0 needs Spring Boot 4.0 or 4.1. For a new project, start with Boot 4 and Spring AI 2.0.
How do I use Spring AI with Ollama?
Run Ollama, pull a model, add the spring-ai-starter-model-ollama starter, and set spring.ai.ollama.base-url and spring.ai.ollama.chat.model in application.properties. Then inject ChatClient.Builder and call the model.
How does Spring AI remember the conversation?
The model itself remembers nothing. Spring AI’s MessageChatMemoryAdvisor stores each conversation’s messages in a ChatMemory and adds them to every new request. You choose the conversation with the ChatMemory.CONVERSATION_ID parameter.
Can I switch from OpenAI to another model without changing code?
Yes, as long as your code uses ChatClient and the shared options in properties. Change the starter dependency and the spring.ai.* properties, and the same code talks to the new provider.
Next in the series
Previous: Java 21 features for AI apps. Next in Core frameworks: LangChain4j, the other big Java AI library, with AI Services, memory and tools. After that, a side-by-side comparison to help you choose.
Comments