Over coffee the other day, a retail PM asked me: “Our system has been written in Java for a decade. Now management wants an AI assistant to look up orders and company policies—does the team have to scrap everything and rewrite it in Python?” Sound familiar? Almost every Java team taking their first steps into AI runs into this exact question.
The Real-World Challenge of Bringing AI into Java Systems
Most core enterprise systems—from order management and HR to accounting—run reliably on Java and Spring Boot. But when an AI requirement lands on the roadmap, engineering teams immediately hit three roadblocks:
- AI tutorials are overwhelmingly written in Python: Search online for how to build a chatbot, and nearly 90% of the guides use Python. Meanwhile, all your business logic, permissions, and database connections live in Java.
- AI sounds great but knows nothing about internal data: Models like GPT or Gemini handle general knowledge effortlessly. But ask “Where is order #8821 right now?” or “What is the 2026 leave policy?”, and the model either hits a wall or hallucinates an answer.
- The operational burden of running another stack: Spinning up a separate Python server just to call AI means maintaining another deployment pipeline, another security layer, and the overhead of syncing data back and forth.
Why Does Integrating AI into Java Feel So Messy?
Think of an LLM as an exceptionally sharp intern. They have read every book on the internet, yet they know nothing about your company. To help them do real work, your team has to solve three technical bottlenecks:
- Every AI provider has a different API: OpenAI, Anthropic Claude, Google Gemini, and locally hosted models all use different request and response formats. Code that works great with OpenAI today will require rewriting most of your integration layer next month if management wants to switch to Gemini to save costs.
- Models cannot directly access live data: At its core, an LLM only generates text. It cannot open PostgreSQL or call an internal REST API to check inventory without an intermediary function-calling mechanism.
- You cannot stuff an entire document repository into a prompt: Company documentation is scattered across PDFs, Word files, and Confluence. Sending a 300-page handbook (roughly 150,000 tokens) with every single question costs a fortune per message and adds ten seconds or more of latency.
Two Common Approaches and Their Bottlenecks
Before settling on a clean architecture, many Java teams try one of these two approaches:
- Calling HTTP APIs directly from Spring Boot: Using
RestClientorWebClientto fire requests to OpenAI. Initial prototyping takes less than half a day. In production, however, you quickly get bogged down parsing nested JSON, handling token-by-token streaming, and rewriting code every time you switch providers. - Spinning up a separate Python microservice: Using FastAPI to handle AI while Spring Boot calls it over HTTP. This works if your company already has a dedicated AI/Data team. For a pure Java team, maintaining a second language slows down feature delivery and adds 30–80ms of network latency on every round-trip back to fetch data.
The Cleanest Solution: Using Spring AI Directly in Spring Boot
If you have worked with Java for years, you are already used to Spring connecting to MySQL, PostgreSQL, or Oracle through a single abstraction like Spring Data JPA. Spring AI brings that exact same philosophy to the LLM world. You write your code once using Spring conventions. Underneath, whether you want to run OpenAI, Gemini, or Ollama locally, you only need to change a few lines of configuration.
On one of our e-commerce projects (running Spring Boot 3.3 and handling around 40,000 orders per month), the team took just 4 days to build a production-ready version. No Python hires needed. All existing JWT authentication, logging, and database setups stayed completely intact.
1. Connect to an LLM in Minutes
Starting with Spring AI 1.0.x, declare the BOM for version management and add the OpenAI starter to your pom.xml (to use Gemini or Ollama, just swap in the corresponding artifact name):
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-model-openai</artifactId>
</dependency>
Next, add your API key and model configuration in application.yml. Setting temperature: 0.3 keeps responses grounded in facts and curbs overly creative hallucinations:
spring:
ai:
openai:
api-key: ${OPENAI_API_KEY}
chat:
options:
model: gpt-4o-mini
temperature: 0.3
All interactions with the LLM go through ChatClient. Create a simple REST controller like the one below, and you are ready to make your first call:
@RestController
@RequestMapping("/api/ai")
public class AssistantController {
private final ChatClient chatClient;
public AssistantController(ChatClient.Builder builder) {
this.chatClient = builder
.defaultSystem("You are a friendly customer support assistant. Answer concisely in English.")
.build();
}
@GetMapping("/ask")
public String ask(@RequestParam String question) {
return chatClient.prompt()
.user(question)
.call()
.content();
}
}
2. Function Calling: Giving AI Hands to Read Real Data
Even the most articulate support agent is helpless without a computer when a customer asks for a tracking number. Function Calling (referred to as Tool Calling in Spring AI) acts as that computer. When a customer asks about an order status, the LLM determines which Java method to invoke, retrieves the real data, and then formats a natural-sounding reply.
All you need to do is create a standard Spring bean and add the @Tool annotation to any method you want to expose to the AI:
@Component
public class OrderTools {
@Tool(description = "Look up order status by order ID")
public String getOrderStatus(String orderId) {
// In production, you would call OrderRepository to query the database
if ("DH8821".equalsIgnoreCase(orderId)) {
return "Order DH8821 is currently out for delivery with the carrier and is expected to arrive today.";
}
return "No information found for order ID " + orderId;
}
}
When calling ChatClient, pass the OrderTools bean via the .tools(...) method:
@GetMapping("/orders/ask")
public String askWithTools(@RequestParam String question, OrderTools orderTools) {
return chatClient.prompt()
.user(question)
.tools(orderTools)
.call()
.content();
}
Now, when a customer asks “Where is my order DH8821?”, Spring AI automatically orchestrates the call so the model triggers getOrderStatus("DH8821"). The response matches your database 100%—no more guesswork.
3. Building a RAG Pipeline for Internal Documents
For questions about company procedures or warranty policies, the answer is RAG (Retrieval-Augmented Generation). Simply put, RAG is like letting the AI take an open-book exam. Instead of forcing the model to digest a 300-page handbook, the system retrieves only the 3–5 most relevant excerpts and attaches them to the prompt.
Implementing RAG in Spring Boot boils down to two steps:
Step 1: Load documents into a Vector Database. Already using PostgreSQL? Just enable the pgvector extension to get a built-in vector store without installing external software (remember to add the spring-ai-pdf-document-reader dependency to read PDFs):
@Service
public class KnowledgeIngestionService {
private final VectorStore vectorStore;
public KnowledgeIngestionService(VectorStore vectorStore) {
this.vectorStore = vectorStore;
}
public void ingestPdf(Resource pdfResource) {
// 1. Read the PDF file content
PagePdfDocumentReader pdfReader = new PagePdfDocumentReader(pdfResource);
// 2. Split the text into appropriately sized chunks
TokenTextSplitter splitter = new TokenTextSplitter();
List<Document> chunks = splitter.apply(pdfReader.get());
// 3. Convert to vectors and save to the database
vectorStore.add(chunks);
}
}
Step 2: Query using an Advisor. Spring AI provides QuestionAnswerAdvisor out of the box. Attach this advisor to ChatClient, and semantic search in your VectorStore plus context injection into the prompt will happen automatically:
@GetMapping("/policy")
public String askPolicy(@RequestParam String question, VectorStore vectorStore) {
return chatClient.prompt()
.user(question)
.advisors(QuestionAnswerAdvisor.builder(vectorStore).build())
.call()
.content();
}
In under 50 lines of Java code, you have a reliable assistant capable of reading internal documents. Your data stays safely within your company’s infrastructure. Later on, if you want to upgrade your model or switch providers, you won’t have to disrupt your existing Spring Boot architecture.

