跪拜 Guibai
← Back to the summary

Spring AI 2.0 GA: The control-plane shift that finally makes Java a first-class AI runtime

Last month I helped a friend's team troubleshoot a production incident: their AI customer service bot went haywire in the middle of the night, calling the refund API 7 times in a row with no circuit breaker and no rate limit, tripling their monthly bill. They were on Spring AI 1.x, with the tool loop buried inside ChatModel — no way to intervene.

This article focuses on one thing: What exactly changed in Spring AI 2.0 GA, and why it is the watershed moment for Java backend AI engineering. It's for Java developers working on AI application delivery or planning to upgrade from 1.x. It's a long read, so bookmark it.


1. Align on the facts: this is not an ordinary upgrade

Let's set the version coordinates first so we don't drift:

image.png

A few key numbers worth remembering:

One sentence summary: This is not a minor version adding APIs; it's a refactor that sinks the agent runtime into the framework. The official positioning is clear: Spring AI wants to be the "JDBC of AI" unified runtime, not a glue collection of model SDKs.


2. The essence of the watershed: control returns from the model to Java

The pain of 1.x is familiar to anyone who's done it. I took over a typical "wild integration" project: Controllers manually built request bodies, tool-call logic scattered across 7 Services, retry + exception handling came to nearly 2000 lines. It ran in a demo, but started hurting in production — the tool loop was hidden inside each ChatModel implementation, memory, retry, masking, and observability were implemented separately, and the code quickly grew into a "private framework" nobody dared touch.

Spring's own assessment of 1.x is "functional, but buried": you can call tools, but you can't build anything on top of tool calls.

What 2.0 overcomes, in one sentence:

The tool-calling loop is extracted from inside the model implementation and promoted to a first-class citizen on the Advisor chain. An AI call changes from "an HTTP request" to "an assembleable, governable pipeline."

Spring's 20 years of Filter / Interceptor / Advisor engineering intuition finally works fully in AI scenarios.

image.png

Here's a detail many miss: Advisor order is carefully designed. MessageChatMemoryAdvisor defaults to HIGHEST_PRECEDENCE + 200, ToolCallingAdvisor defaults to +300 — so memory sits outside the tool loop by default, and multi-turn tool calls share the same session context instead of each turn getting a "forgetful" new conversation.

The recursion mechanism is also clean: ToolCallingAdvisor re-enters the downstream chain after executing a tool, until the model returns a response without a tool call. The same re-entry mechanism also handles "structured output self-correction retry."

Official test data: the new tool-calling architecture reduces token consumption by 34%–64% on OpenAI, Anthropic, and Gemini. Because tool definitions and loop management no longer "leak" through each model implementation.


3. The real chain of a single tool call

With the architecture in mind, look at what a production-grade tool call looks like:

image.png

One thing to burn into your brain from this chain:

The model only proposes "what tool I want to call and what parameters," the actual execution is done by the Java application, not the model.

So when the model says "refund," it doesn't mean the system should refund. Permissions, parameters, business state, idempotency, and second confirmation must still be controlled by the backend. The model decides "what to do," the application does "actually doing it and making it auditable" — 2.0 writes this boundary into the framework contract for the first time.


4. Core code: four snippets to understand 2.0

4.1 Tool declaration: descriptions for the model, boundaries stay in Java

A tool is just an annotated method; JSON Schema is auto-generated by the framework (1.x's @Function is renamed to @Tool):

@Component
class OrderTools {

    private final OrderService orderService;

    OrderTools(OrderService orderService) {
        this.orderService = orderService;
    }

    // description is a prompt sent to the model, not a comment for humans
    @Tool(description = "Query the current logged-in user's own order status, does not execute refunds or modifications")
    OrderView queryOrder(
            @ToolParam(description = "Order number, e.g. ORD-1001") String orderNo,
            ToolContext toolContext) {

        // Highlight 1: user identity is passed in from the server, never trust a model-generated userId
        Long userId = (Long) toolContext.getContext().get("userId");

        // Highlight 2: join query with order number + user identity to prevent horizontal privilege escalation
        return orderService.findOwnedOrder(orderNo, userId)
                .orElseThrow(() -> new BusinessException("Order not found or no access"));
    }

    @Tool(description = "Only create a refund application, never execute a deduction")
    RefundApply requestRefund(String orderId, String reason, ToolContext ctx) {
        // Write operations only produce "pending review tickets": idempotency key + manual confirmation before actual execution
        String idem = ctx.getContext().get("traceId") + ":refund:" + orderId;
        return refundService.apply(idem, orderId, reason);
    }
}

Three practical points:

4.2 Assembly and invocation: strong type at entry, strong type at exit

@Bean
ChatClient chatClient(ChatClient.Builder builder, OrderTools orderTools, ChatMemory chatMemory) {
    return builder
        .defaultSystem("You are an enterprise knowledge base assistant. Only answer based on tool results; if a query fails, state it explicitly; do not fabricate.")
        .defaultAdvisors(
            MessageChatMemoryAdvisor.builder(chatMemory).build()
            // ToolCallingAdvisor is auto-registered by DefaultChatClient; no need to manually new
        )
        .build();
}

OrderAnswer ask(String question, Long loginUserId) {
    return chatClient.prompt()
            .user(question)
            .tools(orderTools)                          // explicitly declare tools per request
            .toolContext(Map.of("userId", loginUserId)) // server-side trusted context
            .advisors(a -> a.param(ChatMemory.CONVERSATION_ID, sessionId)) // required!
            .call()
            .entity(OrderAnswer.class, spec -> spec.schemaValidation()); // Schema validation self-correction
}

record OrderView(String orderNo, String status, String amount) {}
record OrderAnswer(String conclusion, List<String> evidence) {}

⚠️ Two traps for 1.x upgrades:

Switching models becomes trivial: change the spring.ai.model.chat: openai line, swap the starter, business code stays unchanged.

4.3 Structured output: turning "parse failure" into "auto-retry once"

record RefundDecision(boolean approve, String reason, double amount) {}

RefundDecision d = chatClient.prompt()
    .user("Order A123 user requests refund, decide whether to approve")
    .call()
    .entity(RefundDecision.class, spec -> spec.strictMode(true));

The framework, when JSON doesn't match the schema, feeds the validation error back to the model and asks it to regenerate, and can auto-adapt to vendor-native modes like OpenAI Structured Outputs / Anthropic forced JSON. The ~200 lines of boilerplate from 1.x for "JSON parsing + exception handling + manual retry" can be deleted.

But remember a boundary: structurally correct is not business correct. schemaValidation() only guarantees "parseable"; business rules like order status, amount, permissions must still be validated in the Java service. In production I'd add a fallback: if two consecutive attempts fail, route to human or a degraded branch, never loop infinitely; for critical scenarios use Bean Validation as a second check, so dirty data never flows downstream into financial systems.

4.4 Tool explosion and loop runaway: two new weapons from 2.0

When tools exceed ~30, stuffing all definitions in lowers accuracy and blows up tokens. 2.0's solution is progressive disclosure:

@Bean
ChatClient agentClient(ChatModel chatModel, OrderTools orderTools) {
    return ChatClient.builder(chatModel)
        .defaultAdvisors(
            // Highlight 1: tools are retrieved on demand; only a search tool is injected at session start, model discovers tools as needed
            ToolSearchToolCallingAdvisor.builder()
                .maxTools(5)
                .searchStrategy(SearchStrategy.VECTOR)   // regex / lucene / vector three-level index
                .build(),
            // Highlight 2: taking "when to stop" back from the model
            ToolCallingAdvisor.builder()
                .toolExecutionEligibilityChecker(ctx ->
                    ctx.toolCallHistory().size() < 10 &&
                    ctx.elapsed().compareTo(Duration.ofSeconds(20)) < 0)
                .build())
        .defaultTools(orderTools)
        .build();
}

ToolExecutionEligibilityChecker is the new loop-termination hook in 2.0. In production I'd always hang max rounds + total timeout + token budget triple insurance; community tests show tool retrieval can save 60–70% tokens in large agent scenarios.

Can also enable via config:

spring:
  ai:
    chat:
      client:
        tool-search-advisor:
          enabled: true
          tool-index-type: vector   # choose regex | lucene | vector based on tool scale

5. MCP enters the framework core: from "can connect" to "can scale"

MCP is 2.0's flagship feature, and it's the source of the official MCP Java SDK's code base. Three key changes:

@McpTool(description = "Query order status")
String orderStatus(@ToolParam String orderId) {
    return orderService.status(orderId);
}

Why is this a watershed? SSE long-lived connections break easily through gateways and replicas are hard to scale — the classic "demos fine, production scary" problem. More importantly, the tools you encapsulate can be reused across frameworks in the future — the protocol dissolves the lock-in risk of technology selection.

Two practical reminders: when MCP returns 401, note that in 2.0 header validation is all lowercase, so use headers.get("authorization"); also MCP's ToolCallbackProvider must be explicitly attached to defaultTools(), it won't auto-register.


6. Production pain points and solutions (the most valuable section of this article)

2.0 gives you the right place to solve problems, but it doesn't mean "production-grade just by using it." Below is a table I compiled from real project pitfalls, worth screenshotting:

Pain Point Field Symptom Solution
Model escaping data access Tricked into querying others' orders Identity from SecurityContext, passed via ToolContext; enforce data-ownership validation at SQL/service layer, not pure prompt constraints
Write operations duplicated Refund triggered twice Split tool into "create operation ticket" and "confirm execution" two-phase; idempotency key (traceId:refund:orderNo) + DB unique constraint + human confirmation + audit log
Agent infinite loop burning money Model repeatedly calls tools without converging ToolExecutionEligibilityChecker sets hard limits (rounds/timeout/budget); after circuit break, route to human
Silent errors Search fails, model confidently passes off guesses as facts RAG similarity threshold filtering + allowEmptyContext control; when context empty, short-circuit to "temporarily unavailable, please contact human" degraded template, forbid model free play
Blind retries amplifying incidents LLM can generate conflicting outputs for the same problem twice Split failure modes by dependency: model timeout -> circuit break + switch to backup model; tool timeout -> return structured error code; no blanket retries
Too many tools hard to select Accuracy drops, tokens rise after 30+ tools ToolSearchToolCallingAdvisor on-demand retrieval + slim tool descriptions + split agents by domain; build a "tool hit rate" dashboard, retire tools not hit long-term
Multi-turn losing tool trace Second turn "forgets" order queried in first Memory Advisor defaults to outer layer of tool loop; if full trace needed, order memory after ToolCallingAdvisor, persist tool messages with JDBC/Mongo
Context bloat Token explosion after dozens of turns MessageWindowChatMemory window memory (evict by turn boundary) + long-session summary compression; dual-track: display history (full) and reasoning history (window)
Wrong answer but HTTP 200 Monitoring all green, users cursing Observability shouldn't just track availability; watch "implicit deviation rate"; trace records retrieval snippets, final prompt, tool trace (masked), support replay
Prompt injection User content treated as instructions Isolate untrusted text with labels; read/write tool whitelist grading; output masking; PDF/image parsing resource limits; include dependencies in SCA scanning
Streaming killed by gateway Local fine, production broken, frontend spinners Tune Nginx/Tomcat/MVC three-layer timeouts together, add heartbeats, disable gateway buffering
Quality not measurable Changing prompts "feels better" with no evidence Evaluation framework with offline eval sets (relevance/factuality 0–1 scores) + CI gate; tag prompt and model versions together, support gray rollback

I want to expand on two points that are most underrated.

First, security aspects finally have the correct mounting point. In 1.x interceptors hang outside the model, so they can't reach inside the tool loop; in 2.0 the tool loop is on the chain, so you actually have the "before tool execution" cut point:

@Component
public class TenantGuardAdvisor implements CallAdvisor {

    @Override
    public ChatClientResponse adviseCall(ChatClientRequest request, CallAdvisorChain chain) {
        // Strip out tools not on the whitelist: tools beyond tenant "can't see" -> won't call
        return chain.nextCall(filterToolsByTenant(request));
    }

    @Override public String getName() { return "tenantGuardAdvisor"; }

    // Order before the tool-calling Advisor
    @Override public int getOrder() { return Ordered.HIGHEST_PRECEDENCE + 100; }
}

Second, observability order determines what you measure. For the same audit Advisor, returning HIGHEST_PRECEDENCE + 10 (wrapping outermost) measures real user latency including retries and RAG; returning +400 (inside ToolCallingAdvisor) measures each model call — multi-round agent bills hide in the latter; if you place it wrong you'll never find where the money went. Also note GA uses getCompletionTokens(), not pre-GA getGenerationTokens().

Testing advice: don't mock ChatClient, that removes the entire behavior under test. The right approach is to lower the mock boundary to ChatModel, use a Stub to run the real Advisor chain, and assert tool-call trajectory, not text — L1 uses Stub to assert trajectory, L2 uses a golden dataset against real models to verify effects; don't mix the two layers.


7. Resilient foundation: streaming, circuit breaking, and virtual thread pitfalls

If this helps, hit "liked" so I know; the next sections are all battle-tested production experience.

Streaming rule: retry before first chunk, never replay after first chunk

For synchronous calls, retrying on 500 is fine, but in streaming, once the first chunk has been sent to the frontend, retrying shows duplicate content to the user. A production-grade multi-model circuit breaker looks like this:

public Flux<ChatResponse> stream(Prompt prompt) {
    AtomicBoolean firstChunkArrived = new AtomicBoolean(false);
    return Flux.defer(() -> pickHealthy().stream(prompt))
        .doOnNext(c -> firstChunkArrived.set(true))
        .retryWhen(Retry.backoff(2, Duration.ofMillis(200))
            // Core: if first chunk sent, disable retry; only continue writing + frontend idempotent splice by requestId
            .filter(e -> !firstChunkArrived.get() && retryable(e)));
}

On the sync side, note: 400 and content-moderation errors don't switch models — switching is pointless and just burns money; only 429 / 5xx / timeouts are worth failover. Models under circuit breaker are skipped directly, no pointless waiting.

Streaming performance metrics have nuances: P99 total latency is meaningless; TTFT (time to first token) is what users feel. Our SLO is TTFT P95 < 800ms, achieved via connection pool warm-up + semantic cache + small-model pre-routing.

SSE disconnect: cancel upstream immediately

@GetMapping("/chat")
public SseEmitter chat(String q, Principal p) {
    SseEmitter emitter = new SseEmitter(120_000L);
    var sub = chatClient.prompt().user(q)
        .toolContext(Map.of("uid", p.getName(), "traceId", MDC.get("traceId")))
        .stream().content()
        .subscribe(c -> send(emitter, c), emitter::completeWithError, emitter::complete);

    emitter.onCompletion(sub::dispose);
    emitter.onTimeout(sub::dispose);  // when user closes the page, cancel upstream, don't pay for ghosts
    return emitter;
}

Virtual thread pinning trap

2.0's baseline is JDK 21; virtual threads are the standard direction (spring.threads.virtual.enabled=true), and IO-heavy scenarios like LLM calls and tool execution benefit significantly. But there's a trap: on JDK 21, virtual threads pin the carrier thread inside synchronized blocks or native calls (only fixed completely after JEP 491). On hot paths use ReentrantLock instead of synchronized, and audit thread models for blocking calls in Advisors. Also put AI calls in a separate thread pool/semaphore, don't share a pool with core transaction paths.


8. Migration guide: ~42 breaking changes, know these before you start

2.0 is built on Boot 4 / Framework 7 / Jackson 3, and Boot 3.x is hard-incompatible. Here are the most painful ones:

Foundation layer:

Spring AI layer (all "silent pitfalls" — no errors but behavior changes):

My migration advice (three steps):

  1. JDK / CI first in a separate branch, get the build environment working;
  2. Boot 3→4 upgrade, mechanical renames via OpenRewrite recipes, but read the diff line-by-line as a PR;
  3. Only then touch Spring AI. Write contract tests for each external payload, compare against expected JSON generated before upgrade; declare all model parameters explicitly, never rely on defaults; run a cost baseline comparison before release (token P95, per-session cost).

Reference data from a real project: compile-time errors took ~3 hours (Builder pattern is friendly), behavioral diff investigation is the bulk, ~5 hours. Total cost about a day and a half.

Don't agonize over the decision: new projects start directly with Boot 4 + Spring AI 2.0, don't migrate from 1.x; old Boot 3 production systems stay on the 1.0.x / 1.1.x maintenance line for security patches, don't force it. If you must, stand up AI capabilities as a separate service behind a gateway, don't touch existing transaction paths.


9. Where to go after 2.0

2.1 is on the way, several directions worth watching: session memory (event-log-style sessions + round-aware compression, solving long-session context bloat), tool call confirmation (HITL human confirmation for high-risk tools), DecisionModel API, MCP "modern" protocol 2026-07-28 (with async client), guardrails (rejection with finish reason). Since 2.0.1, tool-call count limits are configurable.

The trend is clear: Spring AI is evolving from a "model access layer" to an "agent runtime foundation." Java backends doing AI finally don't have to envy Python's LangChain ecosystem.


10. Wrap-up: if I were landing this, what would I do in week one?

This is a long article; here are the key points condensed into three sentences:

  1. The essence of the watershed is control: tool loop, memory, structured correction, observability finally stand on the same composable abstraction; AI calls can be governed like Spring pipelines;
  2. The model only proposes, Java backs it up: permissions, idempotency, transactions, audit must be implemented in tool implementations and Advisor chains; don't trust model-passed parameters;
  3. 2.0 gives you the place, governance is yours to build: SLO, cost accounting, eval sets, circuit breaking, degradation — these are where the gap widens.

If I were landing in a new project, week one wouldn't touch vector databases or tune prompts; instead I'd do three "unsexy but life-saving" things:

One last, slightly unpopular but valuable sentence: for fixed three-step approval flows, don't use an Agent; a state machine is cheaper and more controllable. Agents are only for scenarios where steps are not fixed and need model judgment.


Interactive question: Where is your team's AI application now — still "demo works" or already building eval sets and cost accounting? What's the deepest pit you've stepped in? Comment below; if likes pass 500, my next article will dissect "how to compress RAG reranking to P99 < 200ms." If useful, follow me; I'll keep updating the Spring AI 2.0 production series.