Java: Spring AI and LangChain4j

The JVM already has what production needs. Add the model carefully and keep the rules in ordinary Java.

BeginnerIntermediateExpert · 12 min read · Last updated:

In short

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.

What was and was not run

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.

Beginner Rules first, model second

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.

Modelproposes a tool call
Tool methodadds trusted identity
Servicechecks rules
Outcomepaid, approval or refused
Only the service can change data.
Intermediate Tools in two libraries

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.

FeatureUse
Default toolsTools offered on every request from a client
returnDirectSend a tool result straight to the caller
Tool confirmationRequire agreement before a tool runs
AdvisorsAdd logging, memory, retrieval or checks around calls
MCP annotationsPublish 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.

ShapeWhen it fits
SequenceSteps always happen in order
LoopRevise until a check passes, with a maximum
ParallelIndependent pieces of work
ConditionalRoute by a rule or classification
SupervisorA 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.

CheckWhere
The reply parses into the typeLibrary, with a failure you must handle
Fields are present and in rangeBean validation or constructor checks
Identifiers exist and belong to the userYour service
Amounts agree with recordsYour 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.

NeedDesign point
Conversation historySeparate by user and conversation; set retention
Document answersFilter by permission during search
Business factsRead from the system of record through a tool
Deletion requestsCover 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.

Expert Testing, upgrading and comparing

Testing

LayerHowExample case
Business servicePlain unit testsAnother customer's order is refused
Tool classCall the method with a test contextMissing identity fails safely
Loop wiringA stand-in model implementing the model interfaceUnknown tool and call limit
BehaviorReal model over an evaluation setRefuses 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.

EventSafe response
Model call times outRetry within a budget; no action has happened yet unless a tool ran
Action call times outLook up the outcome by operation identifier before retrying
Tool call limit reachedReport that the task stopped; hand to a person if needed
Instance restarts mid-taskResume from stored state, or report clearly
A model turn can repeat tools

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.

  1. Pin versions with the project's bill of materials or your build's dependency management.
  2. Read upgrade notes for both the framework and Spring Boot.
  3. Upgrade in a branch and run offline tests, then the evaluation set.
  4. Compare tool schemas sent to the model before and after.
  5. Release gradually and keep the previous build ready.

Java agent frameworks compared

AspectSpring AILangChain4j
Home groundSpring and Spring BootLibrary with integrations for several frameworks
Programming styleFluent client and advisorsDeclared interfaces and builders
Tools@Tool, @ToolParam@Tool, @P
Multi-agent supportCompose with advisors and your code; further support plannedAgentic module, experimental
Check carefullySpring version requirementsModule 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

SituationSuggested start
Spring Boot servicesSpring AI
Quarkus or plain JavaLangChain4j and its framework integration
Long business processesYour workflow engine, calling either library for model steps
One summarizing callA provider's Java client may be enough
Illustrative design, not a real system

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

MistakeBetter practice
Rules written in the system promptEnforce them in services
User identifier as a tool argumentPass it from trusted server context
Shared chat memorySeparate memory per user and conversation
No tool call limitSet one and test it
Depending on experimental modules everywhereIsolate them
Copying 1.x examples into 2.xCheck 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

Next steps