Imagine you are building a Spring Boot application.
You already know how to create REST APIs, connect to databases, implement business logic, and handle requests.
Now imagine adding one more feature:
A user sends a question to your application, and your application generates an intelligent response using an AI model.
For example:
- User: Explain Java interfaces with an example.
- AI: An interface in Java is a contract that defines methods a class must implement...
How would you implement this?
You could directly call an AI provider's REST API using Java's HTTP client. But then you would need to manage API requests, authentication, request formats, response parsing, and provider-specific details yourself.
This is where Spring AI comes in.
Spring AI provides abstractions and integrations that make it easier to connect Spring Boot applications with AI models.
In this blog, we'll understand Spring AI by building a small project: Java Concept Explainer.
We'll create a REST API that accepts a Java-related question and returns an AI-generated explanation.
Let's start!
Table of Contents
- The problem: Connecting Java applications with AI models
- What is Spring AI?
- Why do we need Spring AI?
- How Spring AI works
- Important Spring AI concepts
- Our project: Java Concept Explainer
- Step 1: Create a Spring Boot project
- Step 2: Add Spring AI dependencies
- Step 3: Configure the API key
- Step 4: Create the service
- Step 5: Create the REST controller
- Step 6: Run the application
- Step 7: Test the API
- Understand the complete request flow
- What happens behind the scenes?
- Can we use a different AI provider?
- Important things to remember
- What's next in Spring AI?
- Common mistakes
- Quick recap
- Try it yourself
The problem: Connecting Java applications with AI models
Let's say you want to add an AI-powered feature to your Spring Boot application.
You decide to use an AI model from an external provider.
Your application needs to:
- Accept a question from the user.
- Send that question to the AI provider.
- Authenticate the request.
- Understand the provider's request format.
- Send the HTTP request.
- Read the response.
- Extract the generated answer.
- Return the answer to the user.
You can implement all of this using Java's HTTP client or Spring's RestClient or WebClient.
But there is a problem.
Different AI providers can have different APIs, request formats, authentication mechanisms, and response structures.
Suppose today you use OpenAI.
Tomorrow, you decide to use Ollama or another supported provider.
You may need to modify the code responsible for communicating with the AI model.
Wouldn't it be better if we had a common programming interface for interacting with different AI models?
That's the problem Spring AI helps solve.
What is Spring AI?
Spring AI is an application framework that brings AI integration into the Spring ecosystem.
It provides a consistent programming model for connecting Java applications with different AI model providers.
Instead of manually implementing HTTP communication with every AI provider, we can use Spring AI abstractions.
For example:
String response = chatClient.prompt()
.user("Explain Java interfaces")
.call()
.content();
That's it!
Spring AI handles the model integration behind the scenes.
It also provides features such as:
- ChatClient API
- Prompt templates
- Structured outputs
- Conversation capabilities
- Tool calling
- Retrieval-Augmented Generation (RAG)
- Vector database integrations
- Multimodal AI
- Model Context Protocol (MCP)
We'll start with the simplest feature: ChatClient.
Why do we need Spring AI?
Let's compare two approaches.
Without Spring AI
You need to handle the communication with an AI provider yourself.
Spring Boot Application
|
v
HTTP Client
|
v
Create JSON Request
|
v
Add Authentication
|
v
Send HTTP Request
|
v
AI Provider
|
v
Receive JSON Response
|
v
Parse Response
|
v
Extract AI Answer
You are responsible for handling provider-specific details.
With Spring AI
Spring AI provides abstractions that simplify this process.
Spring Boot Application
|
v
ChatClient
|
v
Spring AI
|
v
AI Model API
|
v
AI Provider
|
v
Generated Answer
You focus on what you want the AI model to do instead of implementing all the communication details yourself.
Important: Spring AI does not eliminate the underlying HTTP communication. It provides abstractions, integrations, and auto-configuration to manage much of that complexity.
How Spring AI works
Before writing code, let's understand a few important concepts.
1. AI Model
An AI model is the actual model that processes input and generates output.
Examples include models provided by:
- OpenAI
- Anthropic
- Ollama
- Amazon Bedrock
Different models support different capabilities, such as text generation, image understanding, embeddings, and audio processing.
Think of an AI model as the engine that performs the actual AI task.
2. Chat Model
A chat model is an AI model designed to process conversational messages and generate responses.
For example:
User: What is Java?
AI: Java is a high-level, object-oriented programming language...
Spring AI provides abstractions for interacting with chat models.
The idea is to make your application less dependent on a particular provider's implementation.
3. Prompt
A prompt is the input or instruction given to an AI model.
For example:
Explain Java inheritance with a simple example.
That is a user prompt.
But prompts can contain more than just user questions.
There are two important message types to understand:
System message
Defines how the AI should behave.
Example:
You are a Java tutor.
Explain programming concepts in beginner-friendly language.
Always provide a simple example.
User message
Contains the actual question asked by the user.
Example:
Explain inheritance in Java.
The system message guides the model's behavior, while the user message provides the task.
4. ChatClient
This is one of the most important concepts in Spring AI.
ChatClient provides a fluent API for communicating with AI chat models.
It allows us to construct prompts, send requests, and retrieve responses.
For example:
String response = chatClient.prompt()
.user("Explain inheritance in Java")
.call()
.content();
Let's understand the methods.
-
prompt()starts building a prompt. -
user()adds the user's message. -
call()sends the request to the AI model. -
content()extracts the generated text.
You can think of ChatClient as the interface your Spring Boot application uses to communicate with an AI chat model.
5. ChatResponse
Sometimes we need more than just the generated text.
For example, we might want response metadata, token usage, or other information about the model's response.
Spring AI provides ChatResponse for accessing richer response information.
For our beginner project, we only need the generated text, so we'll use:
.content()
We'll explore richer response objects in advanced Spring AI topics.
Our project: Java Concept Explainer
Let's build something practical.
We'll create a simple REST API that explains Java concepts using an AI model.
Imagine a user sends:
Explain polymorphism in Java with an example.
Our application sends the question to an AI model.
The model generates an explanation, and our API returns it.
Project architecture
User
|
|
v
GET /api/assistant
|
v
AssistantController
|
v
AssistantService
|
v
ChatClient
|
v
Spring AI
|
v
OpenAI Model
|
v
Generated Response
|
v
User
We'll use:
- Java
- Spring Boot
- Spring AI
- Spring Web
- An OpenAI chat model
Let's implement it step by step.
Step 1: Create a Spring Boot project
Open:
Select the following dependencies:
- Spring Web
- OpenAI (Spring AI model integration)
For the current stable Spring AI 2.1.x release, use a compatible Spring Boot 4.2.x project and Java 17 or later.
If you're working on an existing Spring Boot 3.5.x application, use the compatible Spring AI 1.1.x release instead.
Don't mix incompatible Spring Boot and Spring AI versions.
Generate the project and open it in your IDE.
Our project structure will look like this:
java-concept-explainer/
|
+-- src/
| |
| +-- main/
| |
| +-- java/
| | |
| | +-- com.example.ai/
| | |
| | +-- JavaConceptExplainerApplication.java
| | |
| | +-- controller/
| | | |
| | | +-- AssistantController.java
| | |
| | +-- service/
| | |
| | +-- AssistantService.java
| |
| +-- resources/
| |
| +-- application.properties
|
+-- pom.xml
Step 2: Add Spring AI dependencies
If you selected the OpenAI dependency through Spring Initializr, the required Spring AI dependencies should already be configured.
For an existing Maven project, Spring AI uses a Bill of Materials (BOM) to manage compatible Spring AI dependency versions.
Add the BOM inside your pom.xml:
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-bom</artifactId>
<version>2.1.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
Then add the OpenAI starter:
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-model-openai</artifactId>
</dependency>
We also need Spring Web:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
The OpenAI starter provides the Spring AI integration required to communicate with an OpenAI chat model.
The Spring AI BOM helps manage the versions of Spring AI modules so that you don't have to specify a version for every Spring AI dependency.
Step 3: Configure the API key
Our application needs authentication to communicate with the OpenAI API.
First, obtain an API key from your OpenAI account.
Never hardcode the API key directly into your Java code or commit it to GitHub.
Set it as an environment variable.
For Linux or macOS:
export OPENAI_API_KEY="your-api-key"
For Windows PowerShell:
$env:OPENAI_API_KEY="your-api-key"
Now open:
src/main/resources/application.properties
Add:
spring.application.name=java-concept-explainer
spring.ai.openai.api-key=${OPENAI_API_KEY}
spring.ai.openai.chat.options.model=gpt-4o-mini
Let's understand these properties.
spring.application.name
Defines the name of our Spring Boot application.
spring.ai.openai.api-key
Provides the API key used to authenticate with the OpenAI service.
spring.ai.openai.chat.options.model
Specifies which chat model we want to use.
The model must be available to your API account.
Notice that we didn't put the actual API key inside application.properties.
Instead, Spring reads it from the environment variable.
This is a better approach for keeping credentials outside your source code.
Step 4: Create the service
Now comes the interesting part.
We need a class that communicates with the AI model.
Create:
AssistantService.java
package com.example.ai.service;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.stereotype.Service;
@Service
public class AssistantService {
private final ChatClient chatClient;
public AssistantService(ChatClient.Builder builder) {
this.chatClient = builder.build();
}
public String explain(String question) {
return chatClient.prompt()
.system("""
You are a helpful Java programming tutor.
Explain Java concepts in simple,
beginner-friendly language.
Whenever possible, include a small
Java code example.
""")
.user(question)
.call()
.content();
}
}
Let's understand what is happening.
Injecting ChatClient.Builder
public AssistantService(ChatClient.Builder builder) {
this.chatClient = builder.build();
}
We are injecting ChatClient.Builder using constructor injection.
Where does this object come from?
Spring AI's auto-configuration creates the builder when the required chat model integration is configured.
We don't need to manually create the builder.
We simply inject it and build our ChatClient.
Defining the system message
.system("""
You are a helpful Java programming tutor.
Explain Java concepts in simple,
beginner-friendly language.
Whenever possible, include a small
Java code example.
""")
This is where we define how the AI should behave.
We are telling the model to behave like a Java tutor.
Notice that we haven't asked a specific question yet.
We are only defining the instructions.
Passing the user's question
.user(question)
This adds the actual question received from the user.
For example:
Explain inheritance in Java.
Calling the AI model
.call()
This sends the prompt to the configured chat model and waits for the response.
Extracting the answer
.content()
This extracts the generated text from the response.
That's our service!
Step 5: Create the REST controller
Now we need an endpoint through which users can communicate with our application.
Create:
AssistantController.java
package com.example.ai.controller;
import com.example.ai.service.AssistantService;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/assistant")
public class AssistantController {
private final AssistantService assistantService;
public AssistantController(AssistantService assistantService) {
this.assistantService = assistantService;
}
@GetMapping
public String askQuestion(@RequestParam String question) {
return assistantService.explain(question);
}
}
Let's understand the controller.
@RestController
@RestController
Marks this class as a REST controller.
Spring automatically converts the returned value into an HTTP response body.
@RequestMapping
@RequestMapping("/api/assistant")
Defines the base URL for our controller.
@GetMapping
@GetMapping
Maps HTTP GET requests to this method.
@RequestParam
@RequestParam String question
Extracts the question parameter from the URL.
For example:
/api/assistant?question=Explain Java inheritance
The value is passed to our controller method.
Finally:
return assistantService.explain(question);
The controller passes the question to the service and returns the generated answer.
Notice how we separated responsibilities:
- Controller handles HTTP requests.
- Service handles application logic.
- ChatClient communicates with the AI model.
This is the same layered architecture we commonly use in Spring Boot applications.
Step 6: Run the application
We have completed the implementation.
Now start the application.
Using Maven:
mvn spring-boot:run
Or use your IDE to run the main Spring Boot application class.
If everything is configured correctly, the application should start on port 8080.
Step 7: Test the API
Let's test our endpoint using Postman or curl.
Request:
curl -G "http://localhost:8080/api/assistant" \
--data-urlencode "question=Explain polymorphism in Java with an example"
Our request reaches the Spring Boot application.
The application forwards the question to the AI model.
The model generates a response.
Example response:
Polymorphism is one of the main concepts
of Object-Oriented Programming in Java.
It means one object can take multiple forms.
For example, consider a parent class
called Animal and two child classes
called Dog and Cat.
Each child class can provide its own
implementation of the sound() method.
Example:
class Animal {
void sound() {
System.out.println("Animal makes sound");
}
}
class Dog extends Animal {
@Override
void sound() {
System.out.println("Dog barks");
}
}
class Cat extends Animal {
@Override
void sound() {
System.out.println("Cat meows");
}
}
The actual response will vary depending on the model and prompt.
Congratulations!
You've built your first AI-powered Spring Boot application using Spring AI.
Understand the complete request flow
Let's connect everything we learned.
Suppose the user sends:
GET /api/assistant?question=What is inheritance?
The request follows this flow:
1. User sends a request
The user calls our REST endpoint.
2. Controller receives the request
AssistantController extracts the question.
3. Service receives the question
AssistantService prepares the prompt.
4. ChatClient processes the prompt
The system instructions and user question are combined into the request.
5. Spring AI communicates with the model
The configured OpenAI integration sends the request to the provider.
6. AI model generates a response
The model processes the input and generates an answer.
7. Response returns to the user
Spring AI extracts the generated content, and our controller returns it as the HTTP response.
User
|
| HTTP Request
v
AssistantController
|
| question
v
AssistantService
|
| system + user prompt
v
ChatClient
|
v
Spring AI OpenAI Integration
|
| API Request
v
OpenAI Chat Model
|
| Generated Response
v
ChatClient
|
v
AssistantService
|
v
AssistantController
|
| HTTP Response
v
User
What happens behind the scenes?
You might be wondering:
We only wrote a few lines of code. How does Spring AI know which model to use? How does it communicate with OpenAI?
This is where Spring Boot auto-configuration comes into the picture.
When we add the Spring AI OpenAI starter, Spring Boot can automatically configure the required components based on the available dependencies and application properties.
The general process looks like this:
- Spring Boot detects the OpenAI starter.
- It reads the configured API key and model properties.
- Spring AI configures the OpenAI chat model integration.
- Spring AI provides a
ChatClient.Builder. - We inject the builder into our service.
- We build a
ChatClient. - The client communicates with the configured model when we call it.
This is why we don't need to manually create an HTTP client or write JSON request and response parsing code for this basic example.
Can we use a different AI provider?
One of the interesting features of Spring AI is that it supports multiple AI model providers.
For example:
- OpenAI
- Anthropic
- Ollama
- Amazon Bedrock
- Mistral AI
- DeepSeek
Let's say we want to move from OpenAI to Ollama.
Ollama allows us to run supported open models locally.
Spring AI provides an Ollama integration.
We can replace the OpenAI starter with the Ollama starter:
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-model-ollama</artifactId>
</dependency>
Then configure the model:
spring.ai.ollama.chat.model=llama3.2
Make sure the selected model is installed and Ollama is running.
The important part is that our service can continue using:
chatClient.prompt()
.user(question)
.call()
.content();
We don't need to rewrite the entire application just because we changed the model provider.
Provider-specific configuration and capabilities can still differ, but Spring AI gives us a common programming interface for many common operations.
Important things to remember
Before moving to advanced topics, remember these concepts:
- Spring AI is an application framework for integrating AI capabilities into Spring applications.
- An AI model processes input and generates output.
- A chat model handles conversational input and output.
- A prompt contains instructions and messages sent to the model.
- A system message guides the model's behavior.
- A user message contains the user's actual request.
- ChatClient provides a fluent API for interacting with chat models.
- ChatClient.Builder is auto-configured by Spring AI when the required model integration is present.
-
call()sends the request and waits for the response. -
content()extracts the generated text.
What's next in Spring AI?
Our project is intentionally simple.
It sends a question to an AI model and returns the answer.
But real-world AI applications need much more than that.
Here are some important Spring AI concepts to learn next.
1. Prompt Templates
Instead of hardcoding instructions, we can create reusable prompts with dynamic values.
For example:
Explain {topic} using a {level} explanation.
The values can be supplied dynamically.
2. Streaming Responses
Currently, our application waits for the complete AI response.
With streaming, we can send the generated response to the client as it becomes available.
This is useful for chat applications where users shouldn't have to wait for the entire response.
3. Structured Output
What if we want the AI model to return a Java object instead of plain text?
For example:
public class JavaConcept {
private String name;
private String definition;
private String example;
}
Spring AI provides structured output capabilities that help map model responses to Java types.
4. Chat Memory and Sessions
Our current application does not remember previous questions.
Every request is independent.
Chat memory and session-based approaches help build applications that maintain conversation context across multiple turns.
The newer Spring AI Session API provides a structured way to manage conversational events.
5. Tool Calling
What if the AI model needs to execute a Java method?
For example:
- Fetch the current weather.
- Check a product's availability.
- Retrieve an employee's details.
- Calculate an order total.
Tool calling allows the model to request the execution of application-provided functions.
6. Retrieval-Augmented Generation (RAG)
Suppose you want to build an AI assistant that answers questions using your own PDF documents.
A normal AI model may not know the contents of those documents.
RAG helps solve this problem.
It retrieves relevant information from your documents and provides that information as context to the AI model.
This is useful for:
- Company knowledge assistants.
- Documentation Q&A.
- Internal support systems.
- Product documentation assistants.
7. Vector Databases
RAG applications often need to find documents based on meaning rather than exact keyword matches.
Vector databases store embeddings and support similarity searches.
Spring AI provides integrations with multiple vector database providers.
8. Model Context Protocol (MCP)
MCP provides a standardized way for AI applications to connect with external tools and data sources.
Spring AI provides support for building MCP clients and servers.
This becomes useful when building applications that need access to external systems and tools.
Common mistakes
1. Thinking Spring AI is itself an AI model
Spring AI is a framework for integrating AI capabilities. It does not generate answers independently.
How to avoid it: Understand the difference between Spring AI and the actual AI model provider.
2. Confusing ChatClient with the AI model
ChatClient is the programming interface used by our application. The actual model performs the generation.
How to avoid it: Remember that ChatClient communicates with the configured chat model.
3. Hardcoding the API key
Putting API keys directly into Java code or committing them to GitHub can expose your credentials.
How to avoid it: Use environment variables or a secure secrets manager.
4. Using incompatible versions
Spring AI releases have compatibility requirements for Spring Boot and Java.
How to avoid it: Check the official compatibility documentation before adding dependencies.
5. Expecting every AI response to be identical
AI-generated responses can vary between requests.
How to avoid it: Use clear prompts, suitable model settings, and validation when your application expects a particular response format.
6. Assuming the AI always returns correct information
AI models can generate incorrect or misleading answers.
How to avoid it: Validate important outputs and avoid trusting generated content blindly, especially in business-critical operations.
Quick recap
- Spring AI simplifies AI integration in Spring Boot applications.
- It provides a common programming interface for supported AI providers.
- ChatClient is the primary API used in our simple example.
- Prompts contain system instructions and user messages.
- Spring Boot auto-configuration creates the required model integration components.
- We built a Java Concept Explainer using Spring Boot and Spring AI.
- We used an AI model to generate answers through a REST API.
- Spring AI also supports streaming, structured output, tool calling, RAG, vector stores, and MCP.
Try it yourself
Now it's your turn.
Practice 1: Improve the Java Concept Explainer
- Ask the model to explain Java concepts in simple language.
- Add a system instruction to always include a code example.
- Ask it to explain the difference between an abstract class and an interface.
- Change the endpoint to accept POST requests with a JSON body.
Practice 2: Add difficulty levels
Modify the application so users can request explanations at different levels:
- Beginner
- Intermediate
- Advanced
Pass the selected level into the prompt.
Practice 3: Build a Java Interview Assistant
Create an application that can:
- Generate Java interview questions.
- Explain the correct answer.
- Provide a code example.
- Generate follow-up questions.
Bonus challenge: Replace the OpenAI integration with Ollama and run a local model without sending prompts to a cloud AI provider.
If this helped, or if you spotted something I should fix, tell me in the comments. I'm still learning too.
Top comments (0)