Java: Spring AI and LangChain4j
The JVM already has what production needs. Add the model carefully and keep the rules in ordinary Java.
Spring AI brings model clients, tool calling, advisors, memory and retrieval to Spring applications. LangChain4j is a Java library that turns an interface into an AI service with tools and memory, with a separate module for agentic workflows that is marked experimental. Choose Spring AI if your services are built on Spring, and consider LangChain4j when you want a library that fits several Java stacks.
What you will learn: how to keep business rules framework-free, declaring tools in both libraries, passing trusted identity, limiting tool calls, composing agents, testing, upgrading and comparing.
Prerequisites: The Agent Loop: Observe, Reason, Plan, Act, Reflect and working knowledge of Java.
Checked against documentation and release announcements in November 2026. Only the first listing, which uses nothing beyond the JDK, was run, on OpenJDK 21. The Spring AI and LangChain4j listings were not compiled or run for this page, because their libraries could not be downloaded. Treat them as outlines and confirm class and method names against the version you use.
Start with plain Java
An agent proposes actions; your code decides whether they happen. Write that decision as ordinary Java with no AI dependency. This refund service checks ownership and amount, demands approval above a threshold and ignores a repeated request.
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/** Business rules in plain Java: no AI library appears here. */
public class Refunds {
sealed interface Outcome {}
record Paid(String orderId, BigDecimal amount) implements Outcome {}
record NeedsApproval(String orderId, BigDecimal amount)
implements Outcome {}
record Refused(String reason) implements Outcome {}
static final class Service {
private final Map<String, BigDecimal> orderTotals;
private final Map<String, Outcome> done = new HashMap<>();
private int payments;
Service(Map<String, BigDecimal> orderTotals) {
this.orderTotals = orderTotals;
}
/** The caller's identity comes from the server, not the model. */
synchronized Outcome refund(String customer, String orderId,
BigDecimal amount) {
var total = orderTotals.get(customer + "/" + orderId);
if (total == null) return new Refused("no such order");
if (amount.signum() <= 0 || amount.compareTo(total) > 0)
return new Refused("amount out of range");
if (amount.compareTo(new BigDecimal("50")) > 0)
return new NeedsApproval(orderId, amount);
String key = orderId + ":" + amount.stripTrailingZeros();
return done.computeIfAbsent(key, k -> {
payments++; // the real side effect
return new Paid(orderId, amount);
});
}
}
public static void main(String[] args) {
var service = new Service(
Map.of("sam/A-17", new BigDecimal("80")));
record Call(String customer, String order, String amount) {}
var calls = List.of(
new Call("sam", "A-17", "25"),
new Call("sam", "A-17", "25.00"), // repeated request
new Call("sam", "A-17", "60"),
new Call("sam", "A-17", "500"),
new Call("alex", "A-17", "25")); // not their order
for (var c : calls) {
var result = service.refund(c.customer(), c.order(),
new BigDecimal(c.amount()));
System.out.println(c.customer() + " " + c.amount() + " -> "
+ result.getClass().getSimpleName()
+ (result instanceof Refused r
? " (" + r.reason() + ")" : ""));
}
System.out.println("payments made: " + service.payments);
}
}
Output:
sam 25 -> Paid
sam 25.00 -> Paid
sam 60 -> NeedsApproval
sam 500 -> Refused (amount out of range)
alex 25 -> Refused (no such order)
payments made: 1
The same refund written as 25 and 25.00 produced one payment, because the key removes trailing zeros. Another customer's request for that order was refused, since the lookup includes the customer. Sealed outcomes make callers handle each case. The example keeps keys in memory and builds them from order and amount, so two genuine refunds of the same sum would be treated as one. A real service stores an operation identifier supplied for each request in a database with a unique constraint.
Spring AI
Spring AI 2.0 reached general availability in June 2026, built on Spring Boot 4.1 and the 2.0 line of the MCP Java SDK. It moved the tool loop into the advisor chain: a tool-calling advisor sends tool definitions, runs requested methods, appends results and calls the model again until no further calls are asked for.
// Spring AI 2.x. Not compiled for this page.
import java.math.BigDecimal;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.chat.model.ToolContext;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
class RefundTools {
private final Refunds.Service service;
RefundTools(Refunds.Service service) {
this.service = service;
}
@Tool(description = "Ask for a refund on one of the customer's orders")
String requestRefund(
@ToolParam(description = "Order reference") String orderId,
@ToolParam(description = "Amount to refund") BigDecimal amount,
ToolContext context) {
var customer = (String) context.getContext().get("customerId");
return service.refund(customer, orderId, amount).toString();
}
}
class Support {
String answer(ChatModel model, RefundTools tools,
String customerId, String question) {
return ChatClient.create(model)
.prompt(question)
.tools(tools)
.toolContext(java.util.Map.of("customerId", customerId))
.call()
.content();
}
}
Annotate methods with @Tool and describe parameters with @ToolParam. The ToolContext parameter carries values such as the customer identifier from your server to the tool without sending them to the model. That keeps identity out of the model's hands.
| Feature | Use |
|---|---|
| Default tools | Tools offered on every request from a client |
returnDirect | Send a tool result straight to the caller |
| Tool confirmation | Require agreement before a tool runs |
| Advisors | Add logging, memory, retrieval or checks around calls |
| MCP annotations | Publish tools, resources and prompts from your application |
Limiting the loop
The reference documentation describes limits on the tool calling manager, per tool and in total, counted for each user turn. When a limit is exceeded you choose between stopping and returning an error to the model.
// Spring AI 2.x, imports omitted. Not compiled for this page.
ToolCallingManager manager = ToolCallingManager.builder()
.maxCallsPerTool(5)
.maxCallsPerTool("requestRefund", 1)
.maxTotalToolCalls(10)
.onLimitExceeded(ToolCallLimitBehavior.THROW)
.build();
Check how the manager is wired in your application and write a test that actually exceeds the limit. A configuration that is never applied looks the same as one that is. Add time and spending limits too, since a few slow or large calls can cost more than many small ones.
LangChain4j
With LangChain4j you declare an interface and let AiServices implement it. Methods marked @Tool, with @P describing parameters, become tools. Memory is added explicitly.
// LangChain4j. Not compiled for this page.
import java.math.BigDecimal;
import dev.langchain4j.agent.tool.P;
import dev.langchain4j.agent.tool.Tool;
import dev.langchain4j.memory.chat.MessageWindowChatMemory;
import dev.langchain4j.model.chat.ChatModel;
import dev.langchain4j.service.AiServices;
import dev.langchain4j.service.SystemMessage;
interface SupportAssistant {
@SystemMessage("Help with orders. Take facts from tools only.")
String chat(String question);
}
class CustomerRefundTools {
private final Refunds.Service service;
private final String customerId; // set by the server per session
CustomerRefundTools(Refunds.Service service, String customerId) {
this.service = service;
this.customerId = customerId;
}
@Tool("Ask for a refund on one of the customer's orders")
String requestRefund(@P("Order reference") String orderId,
@P("Amount to refund") BigDecimal amount) {
return service.refund(customerId, orderId, amount).toString();
}
}
class AssistantFactory {
SupportAssistant create(ChatModel model, CustomerRefundTools tools) {
return AiServices.builder(SupportAssistant.class)
.chatModel(model)
.tools(tools)
.chatMemory(MessageWindowChatMemory.withMaxMessages(20))
.build();
}
}
Here the customer identifier is fixed when the tool object is created, so create it for each authenticated session and never share one between users. Chat memory also needs separation by user; the library supports memory selected by an identifier, which your server must derive from the signed-in user. Set a limit on tool rounds using the option your version provides.
Agentic workflows
The langchain4j-agentic module treats agents as AI services that can be combined, created through builders such as AgenticServices.agentBuilder(). The documentation marks the whole module experimental, so its interfaces may change between releases.
| Shape | When it fits |
|---|---|
| Sequence | Steps always happen in order |
| Loop | Revise until a check passes, with a maximum |
| Parallel | Independent pieces of work |
| Conditional | Route by a rule or classification |
| Supervisor | A model chooses which agent acts next |
Where a step is deterministic, write it in Java. Isolate experimental APIs in one package so that a change affects little else.
Typed answers
Java code works best with objects. Spring AI's client can map a reply onto a class or record, and a LangChain4j AI service can declare a record or enum as its return type. Under the surface the model is asked for a particular format and the library parses it.
| Check | Where |
|---|---|
| The reply parses into the type | Library, with a failure you must handle |
| Fields are present and in range | Bean validation or constructor checks |
| Identifiers exist and belong to the user | Your service |
| Amounts agree with records | Your service |
A parsed object is untrusted input. Give it its own type, such as a proposed refund, and convert it to a command only after checks pass. That makes it hard to skip validation by accident.
Memory and retrieval
Both libraries offer conversation memory and retrieval over vector stores. For new Spring AI 2.1 work, use the Session API, because ChatMemory is deprecated. A window of recent messages is simple, but it can drop an instruction or a fact the task still needs. Keep essential facts in your own records and supply them each turn.
| Need | Design point |
|---|---|
| Conversation history | Separate by user and conversation; set retention |
| Document answers | Filter by permission during search |
| Business facts | Read from the system of record through a tool |
| Deletion requests | Cover history, embeddings, logs and caches |
If you use an existing database for vectors, test search quality and index maintenance with realistic volumes. Agent Memory Types and Persistence explains the kinds of memory.
Testing
| Layer | How | Example case |
|---|---|---|
| Business service | Plain unit tests | Another customer's order is refused |
| Tool class | Call the method with a test context | Missing identity fails safely |
| Loop wiring | A stand-in model implementing the model interface | Unknown tool and call limit |
| Behavior | Real model over an evaluation set | Refuses a request outside policy |
Both libraries define a model interface that a test can implement to return prepared tool calls. Keep those tests in the ordinary build so an upgrade that changes behavior is caught early.
Running in production
- Model calls have timeouts, bounded retries and a circuit breaker
- Blocking calls do not exhaust request threads under load
- Pending approvals and operation identifiers are stored durably
- Metrics and traces include model, tokens, tool names and outcomes
- Prompts and results are not logged unless data owners agree
- Secrets come from a secret store, not property files in source control
Existing Java strengths help here: transactions, identity frameworks, connection management and monitoring all apply to tool code. Reliable Tool Execution and Error Recovery covers retries around actions.
Retries and duplicates
Many Java services already retry failed calls through a library or gateway. Add model-client retries on top and one user request may become many. Choose one layer for each kind of retry, and make actions safe to repeat.
| Event | Safe response |
|---|---|
| Model call times out | Retry within a budget; no action has happened yet unless a tool ran |
| Action call times out | Look up the outcome by operation identifier before retrying |
| Tool call limit reached | Report that the task stopped; hand to a person if needed |
| Instance restarts mid-task | Resume from stored state, or report clearly |
Restarting a whole request replays the conversation, and the model may call the same tool again or choose different arguments. Protection has to live in the service that performs the action.
Upgrades
Spring AI 2.0 introduced breaking changes from 1.1.x, so follow the upgrade notes. Spring AI 2.1.0 and 2.0.3 were released on November 20, 2026, with security fixes, some of which change behavior. Version 2.1 is built on Spring Boot 4.2 and deprecates ChatMemory, its advisors and its repositories, for removal in 3.0.0; the new Session API replaces them. The same announcement said that Spring AI Agent, a project for composing and orchestrating agents, would start incubating in early December, with a merge into Spring AI 3.0 planned for the following year. Plans can change; depend on released, supported versions for production.
- Pin versions with the project's bill of materials or your build's dependency management.
- Read upgrade notes for both the framework and Spring Boot.
- Upgrade in a branch and run offline tests, then the evaluation set.
- Compare tool schemas sent to the model before and after.
- Release gradually and keep the previous build ready.
Java agent frameworks compared
| Aspect | Spring AI | LangChain4j |
|---|---|---|
| Home ground | Spring and Spring Boot | Library with integrations for several frameworks |
| Programming style | Fluent client and advisors | Declared interfaces and builders |
| Tools | @Tool, @ToolParam | @Tool, @P |
| Multi-agent support | Compose with advisors and your code; further support planned | Agentic module, experimental |
| Check carefully | Spring version requirements | Module maturity and version alignment |
Note that both define an annotation named Tool in different packages. Importing the wrong one can leave a method silently unregistered or fail at start-up, so check imports when copying examples.
Recommendations
| Situation | Suggested start |
|---|---|
| Spring Boot services | Spring AI |
| Quarkus or plain Java | LangChain4j and its framework integration |
| Long business processes | Your workflow engine, calling either library for model steps |
| One summarizing call | A provider's Java client may be enough |
An insurer adds a claims helper to a Spring service. The model can look up claims and propose payments. The existing payment service keeps its authorization and approval rules, and the new code consists of two tool methods, limits and tests.
Common mistakes
| Mistake | Better practice |
|---|---|
| Rules written in the system prompt | Enforce them in services |
| User identifier as a tool argument | Pass it from trusted server context |
| Shared chat memory | Separate memory per user and conversation |
| No tool call limit | Set one and test it |
| Depending on experimental modules everywhere | Isolate them |
| Copying 1.x examples into 2.x | Check the upgrade notes |
Checklist
- Business rules compile and test without any AI library
- Identity reaches tools from the server only
- Actions use operation identifiers that prevent repeats
- Loop, time and cost limits are set and tested
- Experimental features are contained
- Upgrades are rehearsed with offline tests and evaluations
Frequently asked questions
Do I need Python to build agents?
No. Both libraries cover tool calling and retrieval in Java. Some evaluation tools are Python-based and can run separately against your service.
Can Java applications use MCP?
Yes. There is a Java SDK, and both libraries document MCP support. Authenticate servers and restrict which tools are exposed.
Which Java version is needed?
It depends on the library and framework versions. Check their requirements; the plain example on this page was run on version 21.
Is virtual threading relevant?
It can simplify waiting on many slow model calls. It does not remove provider rate limits, timeouts or the need to bound concurrency.
References and further reading
- Spring AI 2.0.0 available now
- Composable tool calling in Spring AI
- Spring AI tool calling reference
- Spring AI 2.1.0 and 2.0.3 announcement
- LangChain4j agents tutorial
Next steps
Choosing Frameworks: Lock-In, Upgrades and Benchmarks
Compare with a fair trial.
Reliable Tool Execution and Error Recovery
Safe retries for actions.
What Is MCP? Hosts, Clients, Servers and Capabilities
Share tools through a protocol.