Spring AI vs LangChain4j: The 2026 Java LLM Architecture Bet, Priced Out
Spring AI or LangChain4j? For 2026 Java LLM integration, I've priced out this "architecture bet"
Recently I helped a friend's team with a technical review. They spent two days arguing over whether to use Spring AI or LangChain4j for LLM integration. Someone said the cost of picking wrong is higher than not picking at all. I half agree. What truly costs you is never the framework choice itself; it's writing framework types into 200 business classes.
This post walks through version foundations, capability gaps, code feel, and production pitfalls for both frameworks, aimed at teams doing Java AI integration or preparing for AI-focused interviews. You'll get three deliverables: a decision tree you can use directly, a set of anti-corruption layer code, and a pitfall checklist.
1. First, a cold shower: these two are not competitors at all
Many people start by memorizing feature lists: both support multiple models, both support RAG, both support tool calling, both support MCP... After memorizing, they still can't pick a winner. That's normal, because the model abstraction layer has long been commoditized. The core capability gap is under 10%.
Their real difference lies in positioning:
- Spring AI is the "AI abstraction layer in the Spring ecosystem", positioned like a JDBC for the AI world. It replicates the PSA (Portable Service Abstraction) pattern—treating LLMs as a DataSource, handling unified calls, key management, timeouts/retries, streaming, observability, and aiming for integration efficiency.
- LangChain4j is the "AI toolbox on the JVM", framework-agnostic, built for Java rather than a Python port, pursuing scenario capability and orchestration freedom.
So this isn't a question of "who has more features" but three things: which ecosystem your code stands in, which layer your orchestration logic is placed on, and which upgrade cost you're willing to pay in three years. Features can be caught up in three months; a framework's origin takes three years to chase.
One-sentence selection guideline: If you're already on Spring Boot and value engineering consistency and observability → Spring AI. If you're on a non-Spring stack (Quarkus/Micronaut/pure Java), need niche models or private deployment, or want fine-grained RAG pipeline tuning → LangChain4j. Not sure → isolate with an anti-corruption layer; don't go bare.
2. The hardest constraint everyone ignores: version ground
Features can be caught up; version bindings cannot be untangled. For 2026 selection, look at this timeline first:
Several key facts, each one a pit:
- Spring AI 2.0 forces Boot 4 + Framework 7 + Jackson 3, incompatible with Boot 3.x. Boot 3.x can only stay on the 1.1.x maintenance line. And Boot 3.5's open-source support ended on 2026-06-30, so "staying on 1.1.x" is a transition strategy, not a long-term answer.
- LangChain4j's starters cover both Boot 3.5+ and Boot 4, with noticeably friendlier version compatibility. The core requires JDK 17+ and doesn't depend on Spring.
- APIs are still drifting: after LangChain4j 1.0,
ChatLanguageModelwas renamed toChatModel; old tutorials' class names are deprecated in new versions. In Spring AI 2.x,ChatMemoryis planned to be replaced by the Session API.
I've seen the most realistic retrospective: the requirement was just "add smart dispatch to a ticket service," but the real consequence three months later was the entire platform upgraded from Boot 3 to Boot 4—and nobody ever formally approved that decision. So iron rule number one: selection reviews must explicitly write "platform upgrade cost" into the proposal. Don't upgrade your whole application framework for one AI feature.
3. A table to see the differences (and the cost of betting wrong)
| Dimension | Spring AI | LangChain4j | Cost of betting wrong |
|---|---|---|---|
| Design center | Spring container as application: auto-config, starters, Bean model | Framework-agnostic core, "built for Java" | Complex orchestration in Spring AI gets suffocated by the Advisor chain |
| High-level API | ChatClient streaming API + Advisor interceptor chain |
AiServices declarative interfaces (like Feign / Spring Data JPA) |
LangChain4j's dynamic proxy layer is hard to unit-test, deep stack |
| DI / wiring | @Bean + application.yml, zero learning cost |
Builder explicit wiring, multiple same-type beans fail at startup | — |
| Model providers | ~8 core, rest via vendor modules | 20+, including Cohere, HuggingFace, Qianfan/Zhipu, local Jlama | For niche models, Spring AI needs custom adaptation |
| Vector stores | ~18 mainstream | 30+, wider community coverage | Same as above |
| RAG | Opinionated, QuestionAnswerAdvisor one-shot, quick to start |
Fine-grained pipeline: retrievers/query rewrites/routing/reranking/aggregation all replaceable | Wrong choice and RAG tuning space shrinks |
| Observability | Native Actuator + Micrometer + OTel, built-in instrumentation | Via metrics module / ChatModelListener, self-couple; guardrails are beta |
Production troubleshooting without traces; incident postmortems rely on guesses |
| Streaming | Native Flux<ChatResponse>, natural backpressure |
Callback-style TokenStream, async still catching up |
Need to bridge Reactor yourself |
| Non-Spring runtime | Strongly depends on Spring | Quarkus first-class, Micronaut, pure Java, GraalVM Native | Choosing Spring AI for non-Spring is asking for trouble |
| Agent orchestration | Advisor + Tools model, multi-agent evolving | Independent agentic module, @SequenceAgent/@ParallelAgent/BlackboardPlanner more mature |
Forcing multi-agent in Spring AI writes lots of glue code |
| Docs/pitfall cost | Official docs relatively complete | Incomplete docs, few examples, often need to read source | Team time eaten by "filling pits" |
| Governance background | Spring team (Broadcom) | Community-led, Red Hat / Microsoft joint security audit | — |
| Protocol support | MCP client + server, jointly maintained official MCP Java SDK | MCP client tool support | Both bet on MCP; this is a tie |
| License | Apache-2.0, Java 17+ | Apache-2.0, Java 17+ | Both commercial-friendly |
Three differences that score interview points and are easiest to ignore in practice:
- The "tax" of abstraction binding: Spring AI assumes the Spring container is your application—smooth inside Spring, a migration tax outside. LangChain4j's core doesn't bind to any web framework; the same code runs across runtimes.
- RAG's minimum replaceable unit: improving retrieval quality depends on a cycle of replace-and-test (changing chunk size, adding a keyword recall path, swapping rerank models). Whether the minimum replaceable unit is one interface or a whole pipeline determines whether you'll keep going when you reach experiment five. LangChain4j's
ContentRetriever/QueryTransformerand aggregation/reranker are more finely split. - The cost of "magic":
AiServicesdeclaratively binds system prompt, memory, RAG, and tools in one interface—business code becomes very clean. But the dynamic proxy layer is thick, stacks are deep when problems arise, unit tests mock an entire wiring chain, and a team without someone who reads source code will suffer.
4. Decision tree: don't memorize parameters, cook by layer
Three new variables for 2026:
- Domestic scenarios: for Qwen/DeepSeek ecosystems, look first at Spring AI Alibaba; model network reachability matters more than feature count. Or use the OpenAI-compatible protocol with a changed
base-urlfor zero-adaptation integration. - Multi-agent collaboration (A2A / Supervisor pattern): LangChain4j's agentic module and LangGraph4j are more aggressive. If complexity is higher still, neither framework should carry it; hand it to a dedicated orchestration runtime (AgentScope Java / Spring AI Alibaba Graph).
- Don't validate with someone else's demo project—demos don't have your permission interceptors, logging aspects, or tenant filters. Those three are what actually hurt in production.
5. Core code: the same task, two different feels
Spring AI: ChatClient + Advisor, RAG is "attached"
@Bean
ChatClient chatClient(ChatModel model, ChatMemory memory, VectorStore vs) {
return ChatClient.builder(model)
.defaultSystem("你是电商客服,只依据检索内容回答,无依据必须说不知道。")
.defaultAdvisors(
MessageChatMemoryAdvisor.builder(memory).build(), // ① multi-turn memory: inject history before request
QuestionAnswerAdvisor.builder(vs) // ② RAG: retrieval results stitched into context
.searchRequest(SearchRequest.builder()
.topK(5).similarityThreshold(0.75).build())
.build(),
new SimpleLoggerAdvisor() // ③ audit: log after response returns
)
.defaultTools(new OrderTool())
.build();
}
// Tool (Function Calling): method is tool, Spring auto-discovers and injects into the calling loop
@Component
public class OrderTool {
@Tool(name = "queryOrder", description = "根据订单号查询物流状态")
public String queryOrder(@P("订单号") String orderNo) {
return orderService.track(orderNo);
}
}
// Structured output: probabilistic model → deterministic Java object
public record RiskAnswer(String content, List<String> refs) {}
RiskAnswer ans = chatClient.prompt().user(q).call().entity(RiskAnswer.class);
# application.yml — model switch via configuration, code unchanged
spring:
ai:
openai:
chat:
options:
model: gpt-4o
temperature: 0.2
Highlight: The Advisor chain is essentially an AI version of Spring AOP—memory, RAG, masking, billing, circuit breaking are all cross-cutting concerns. Order is semantics, and living in the container naturally reuses interceptor thinking and Micrometer observability. Switching OpenAI → Ollama is basically a Starter + YAML change. In 2.0, the tool-calling loop is extracted as
ToolCallingAdvisor, supporting loop re-entry into downstream chains—model calls tool → result returns → decide again, the whole lifecycle managed by Advisors. That's the prototype of agent orchestration.
LangChain4j: AiServices declarative interface, the interface is the agent
interface SupportAgent {
@SystemMessage("依据检索内容回答,标注来源,无依据则说不知道")
String chat(@MemoryId String sessionId, @UserMessage String q);
@Tool("按工单号查最近一次人工复核结论")
ReviewResult lookup(@P("工单号") String ticketId);
}
SupportAgent agent = AiServices.builder(SupportAgent.class)
.chatModel(model)
.chatMemoryProvider(id -> TokenWindowChatMemory.withMaxTokens(4000, tokenizer))
.retrievalAugmentor(DefaultRetrievalAugmentor.builder()
.queryTransformer(new CompressingQueryTransformer(model)) // coreference resolution: "it" → "iPhone 17"
.queryRouter(new DefaultQueryRouter(pgRetriever, esRetriever)) // vector + BM25 hybrid recall
.contentRetriever(EmbeddingStoreContentRetriever.builder()
.embeddingStore(store)
.maxResults(5).minScore(0.72) // hard threshold, don't let low-score fragments pollute context
.build())
.contentAggregator(new ReRankingContentAggregator(scoringModel)) // rerank
.build())
.tools(orderTools)
.build();
String reply = agent.chat("u_10086", "我的订单到哪了?");
Highlight:
@SystemMessage,@UserMessage,@MemoryId,@Tooldeclarative composition. The caller sees an ordinary Java interface, with no model concepts exposed. And explicit wiring fails at startup when multiple same-type components exist—moving "which model am I using" from runtime to startup is far safer than "it runs but uses a model you didn't think." The cost, as noted:maxResults/minScoreare exposed at the wiring layer, so tuning RAG parameters requires editing wiring code, which isn't as pluggable as Advisors.
6. The real bet: demote "framework selection" to "swap adapters"
This is the section I most want you to remember. Our measured data from a 120k-line codebase:
Actual change cost to switch frameworks
Without ACL ████████████████████ ~18 person-days (200+ direct references + full regression)
With ACL ███ ~2 person-days (2 adapters + contract tests green)
The approach is the classic Anti-Corruption Layer (ACL). No AI framework import is allowed above the red line.
Port definition—return values are domain records, no ChatResponse, AiMessage:
public interface LlmPort {
Answer ask(ChatCommand cmd);
Flux<String> stream(ChatCommand cmd); // Reactor is infrastructure, acceptable
}
public record ChatCommand(String conversationId, String tenantId,
String query, Map<String, Object> filters, int maxTokens) {}
public record Answer(String text, List<Citation> citations, long tokens, long costMicros) {}
Dual adapters + conditional wiring, switch by one config line:
@Component
@ConditionalOnProperty(name = "llm.engine", havingValue = "spring-ai", matchIfMissing = true)
class SpringAiAdapter implements LlmPort {
private final ChatClient chatClient;
@Override
public Answer ask(ChatCommand c) {
ChatResponse r = chatClient.prompt().user(c.query())
.advisors(a -> a.param(ChatMemory.CONVERSATION_ID, c.conversationId())
.param("tenant", c.tenantId())) // tenant isolation, prevent cross-tenant leakage
.options(ChatOptions.builder().maxTokens(c.maxTokens()).build())
.call().chatResponse();
return AnswerMapper.from(r); // the only place framework → domain translation happens
}
}
@Component
@ConditionalOnProperty(name = "llm.engine", havingValue = "langchain4j")
class LangChain4jAdapter implements LlmPort { /* AiServices implements the same port */ }
A subtle LangChain4j pitfall: its TokenStream is callback-based; bridging to Reactor requires manual work:
@Override
public Flux<String> stream(ChatCommand cmd) {
// Bridge callback-style TokenStream to Reactor, upstream unaware
return Flux.create(sink -> assistant.chat(cmd.query(), cmd.conversationId())
.onNext(sink::next)
.onComplete(sink::complete)
.onError(sink::error)
.start(), FluxSink.OverflowStrategy.BUFFER);
}
Add a gray-release router so "wrong choice" is rollback-able:
public AiReply chat(AiRequest req) {
String target = gray.hit("ai-adapter", req.ctx().get("userId")) ? "langchain4j" : "spring-ai";
try {
return adapters.get(target).chat(req);
} catch (Exception e) {
log.warn("adapter {} failed, fallback", target, e);
return adapters.get("spring-ai").chat(req); // fallback chain
}
}
Finally, seal the boundary with ArchUnit—this earns the most points in a review:
@AnalyzeClasses(packages = "com.acme")
class BoundaryTest {
@ArchTest // anyone importing framework classes in business layer gets CI red
static final ArchRule ACL = noClasses().that().resideInAnyPackage("..domain..", "..app..")
.should().dependOnClassesThat()
.resideInAnyPackage("org.springframework.ai..", "dev.langchain4j..");
}
Tradeoff of the ACL must be clear: an abstraction layer loses advanced framework features (e.g., Advisor chain). My approach is to abstract only the stable minimum set (chat, tools, retrieval), and allow framework-specific orchestration to leak through the port, rather than forcing a big-and-all interface. Also leave a
Map<String,Object> providerOptionsin the port, converted to native parameters likeOpenAiChatOptionsin the adapter; otherwise private parameters likereasoningEffortandthinkingBudgetget eaten by the unified abstraction when you switch models.
Exit cost doesn't look at total dependencies but at the number of exclusive libraries only that framework uses. As long as the business layer guards the port, switching frameworks is one config line plus rewriting one adapter—even a wrong bet can be rolled back in a week.
7. Production hard bones (frameworks don't finish these for you)
7.1 Thread model: 50 concurrent requests can take down your service
A real incident: under a traditional Tomcat 200-thread pool, just 50 concurrent AI requests drove the service into near-death. A single LLM request hangs for 5–30 seconds, threads get monopolized, health checks can't respond, and K8s LivenessProbe fails, restarting the Pod.
Load test numbers are straightforward:
| Scenario | Throughput | Note |
|---|---|---|
| Tomcat 200 platform threads, 500 concurrent, 5s response | ~40 req/s | CPU sys% spikes, thread pool queuing |
| Same scenario + Java 21 virtual threads | ~480 req/s | 12x throughput, CPU overhead nearly flat |
| Another 500-concurrency test | 21 → 325 req/s | P95 24.14s → 1.52s |
Adoption guideline: For existing Spring MVC teams, JDK 21 + virtual threads is the highest cost-performance thread model for AI scenarios, rather than forcing WebFlux. WebFlux solves blocking but carries too high debugging complexity and context propagation cost. Virtual threads let you reuse existing filters, interceptors, ThreadLocal chains. Upgrading to Boot 4 + Java 21 gets this dividend along the way—the "extra profit" that convinces the architecture group to approve.
spring:
threads:
virtual:
enabled: true # Tomcat requests run on virtual threads (Boot 3.2+)
But there's a pitfall that must be known: on JDK 21, virtual threads can pin the carrier thread inside synchronized blocks or certain native calls. Some HTTP clients (like OkHttp/okio) trigger pinning in Spring AI call chains, nullifying virtual thread advantages or even causing deadlock. Solutions: replace synchronized in the AI call chain with ReentrantLock, load-test HTTP clients to verify; if pinning is uncontrollable, fall back to a dedicated AI thread pool + semaphore throttling as a bulkhead, so long AI requests don't pollute the main business thread pool.
@Bean("aiExecutor")
Executor aiExecutor() {
return new ThreadPoolTaskExecutor() {{
setCorePoolSize(16); setMaxPoolSize(64);
setQueueCapacity(200); setRejectedExecutionHandler(new CallerRunsPolicy());
}};
}
7.2 RAG tuning: from "can retrieve" to "reproducible"
When a knowledge-base Q&A system answers irrelevantly after launch, it's usually because the retrieval chain isn't decomposed cleanly. Split the chain into seven independently replaceable stages, leave an interface for each:
- Chunking strategy: split by semantics/heading hierarchy, keep metadata (department, doc version, effective time); hard filters first narrow the scope before similarity calculation.
- Cost control: query rewriting, expansion, and reranking each cost one model call; three together can be more expensive than the final generation. First get "chunking + hard filters" right (these two free things solve about 70% of the problem), then add rewriting/reranking; use RRF for fusion, and connect a Rerank model for precision when necessary.
- A/B reproducibility: fix a set of evaluation questions; every time you replace one stage, run hit rate / citation accuracy; do stage-by-stage A/B by swapping only one implementation class, avoiding tuning by feel.
- Dialect pitfall: filter syntax differs across vector stores; switching from pgvector to ES breaks everything. Build a self-made
FilterExpressionConverterto translate uniformly at the adapter layer.
7.3 Tool count explosion: progressive disclosure is the 2026 standard
After hooking up dozens or hundreds of tools, the model picks the wrong tool frequently and the context gets consumed by tool descriptions. Three layers of solutions:
- Progressive tool disclosure: group and mount tools by scenario/role; route to sub-domain first, then expose the corresponding tool set. Spring AI 2.0 natively supports this:
# Over 30 tools saves 34%~64% tokens; enterprise agent scenarios measured 60%~70%
spring.ai.chat.client.tool-search-advisor.enabled=true
spring.ai.chat.client.tool-search-advisor.tool-index-type=vector
- Externalize tools via MCP: wrap stable internal capabilities as MCP Servers; the model side keeps only references, avoiding tool definitions permanently residing in the prompt.
- Write operations must have a fallback:
@Tooltriggers a DB write on LLM retries—that's a real crash scene. Add idempotency keys + local transactions at the tool layer; never hand transactions to the model orchestration. Write operations (order placement/refunds) must have human-approval guardrails; server-side secondary authentication and tool whitelist prevent prompt-injection privilege escalation.
7.4 Hallucination and structured output: production-grade "three lines of defense"
Model output missing fields, malformed formats, fabricated citations—downstream parsing crashes. Combine three lines:
// ① Structured output + JSON Schema constraint + validation retry
BeanOutputConverter<OrderAdvice> converter = new BeanOutputConverter<>(OrderAdvice.class);
OrderAdvice advice = retryTemplate.execute(ctx ->
converter.convert(chatClient.prompt()
.user(t -> t.text("分析订单 {order},按schema输出").param("order", order))
.param("format", converter.getFormat()) // inject JSON Schema
.call().content()));
Assert.isTrue(advice.getConfidence() > 0.6, "置信度不足,转人工");
// ② Token budget guard: overspending in a single session short-circuits before hitting the model
class BudgetGuardAdvisor implements CallAdvisor {
public ChatClientResponse adviseCall(ChatClientRequest req, CallAdvisorChain chain) {
String cid = (String) req.context().get(ChatMemory.CONVERSATION_ID);
if (meter.used(cid) >= budget) throw new BudgetExceededException(cid); // degrade to human
ChatClientResponse resp = chain.nextCall(req);
meter.record(cid, resp.chatResponse().getMetadata().getUsage().getTotalTokens());
return resp;
}
public int getOrder() { return Ordered.HIGHEST_PRECEDENCE; } // must be outermost
}
// ③ Bulkhead isolation: AI call thread pool separated from business thread pool, LLM jitter doesn't drag down main path (see 7.1)
Two more lessons: front-load input guardrails (including prompt-injection detection); output validation via synchronous extraction; streaming only exposes "draft-state" text—otherwise when output guardrails require regeneration, the stream has already emitted half. On validation failure, feed the error back into the prompt for self-correction (Spring AI 2.0 has this built-in), set a hard retry limit, and write failures to a dead-letter queue. Force refs citation numbering; after generation, check the answer lands within recalled fragments; if uncertain, answer "knowledge base does not cover," don't fabricate.
7.5 Multi-turn memory and context budget
The longer the conversation, the more history stuffed into the prompt, linearly increasing token cost and latency; after 50 turns cost can rise 10x. Solutions:
- Sliding window + summary compression:
MessageWindowChatMemorylimits count,TokenWindowChatMemorylimits tokens; when threshold exceeded, compress early history into a summary. Persist history but don't send it all to prompt; retrieve on demand. - Session isolation:
@MemoryId/ user-dimension isolation prevents cross-account mixing; tenant parameters passed explicitly; sensitive sessions expire and clean up. - Context budget management: set limits for system prompt, recalled fragments, and history separately; trim token budget before assembly.
- Version warning: Spring AI 2.x plans to replace
ChatMemorywith the Session API in 2.1. Best to wrap memory in your ownConversationMemoryPortwith Redis management, keeping the framework's memory API from leaking out.
7.6 Three streaming pitfalls
- Backpressure: callbacks emit fast, gateway
Fluxconsumes slow → OOM. UseFlux.create+onBackpressureDrop+ a unified rate limit. - Streaming + tool calls: under SSE, tool_call fragments can aggregate incorrectly. Run the tool loop non-streaming, then stream text output;
doOnCancelactively cancels upstream + heartbeat keepalive—otherwise if the user closes the page, upstream still burns tokens. - Streaming billing inaccuracy: usage is only in the final chunk; mid-stream disconnects record cost as 0. Enable
include_usage; on disconnect, estimate with tokenizer and mark it.
7.7 Observability and cost: instrument from day one
If you don't know where it's stuck or discover token overspend on the month-end bill, it's because Day-one instrumentation was missing:
- Connect Micrometer, record token usage (input/output), time-to-first-token (TTFT), total latency, retrieval hit rate, tool call count, degradation count.
- Weave one Q&A's "retrieval → prompt assembly → model call → tool callback" into a single trace, tagged with
gen_ai.*semantic attributes via OTel, to locate whether retrieval or model is the bottleneck. - Build your own LLM call logging middleware outside the framework: record prompt, model, token in/out, latency, traceId for audit reproducibility.
- Set per-user/tenant token quotas and circuit breakers; cache high-frequency questions; degrade slow calls. During peak sale events with model 429/jitter, use Resilience4j exponential backoff + jitter, Bulkhead isolation, multi-key/multi-vendor failover.
7.8 Dual-framework coexistence: possible, but with rules
Bringing both frameworks into one service causes same-named beans (chatModel, embeddingModel, vectorStore) to override each other; Spring AI 2.0 ships Jackson 3, LangChain4j still lives in Jackson 2, dependency conflicts. Rules:
- In principle, one service picks one framework; don't hard-mix in the same JVM to "take the best of both."
- If you truly coexist, split by layer: Spring AI handles access and engineering; LangChain4j handles complex retrieval and orchestration, and only one auto-config set manages ChatModel. In LangChain4j's Spring integration, use
wiringMode = EXPLICITto reuse model Beans in the container, avoiding two HTTP clients and two key-management systems:
@AiService(
wiringMode = EXPLICIT,
chatModel = "openAiChatModel", // reuse the connection in Spring container
chatMemoryProvider = "memoryProvider",
contentRetriever = "milvusRetriever"
)
public interface RagAssistant {
@SystemMessage("只依据检索内容回答,无依据则说不知道")
String ask(@UserMessage String q);
}
- Dependency isolation: separate modules or processes; bring
mvn dependency:treeinto CI as a gate; share a unified trace ID and align metric names, otherwise two observability stacks split troubleshooting.
8. Localization and "safe bet" posture
The easiest way to connect domestic models (Qwen/DeepSeek/GLM) is the OpenAI-compatible protocol with a changed base-url; both frameworks work with zero rework:
spring:
ai:
openai:
api-key: ${DASHSCOPE_API_KEY}
base-url: https://{WorkspaceId}.cn-beijing.maas.aliyuns.com/compatible-mode/v1
chat:
options:
model: qwen4-max # or deepseek-chat
Note regression cases must cover multi-turn reasoning_content replay—domestic models' OpenAI compatibility varies; the loss of reasoning fields is a real issue (2.0 has fixed related bugs). For deep Qiwen ecosystem binding, go directly to Spring AI Alibaba, which also gains Nacos dynamic Prompt, Graph orchestration, and other localized capabilities.
The last step of selection isn't making a decision; it's running an A/B experiment:
- Shadow dual-run: run the same golden set (e.g., 300 real customer questions) through both Adapters, compare answers and latency.
- Hash by userId, gray 5%; ⚠️ the same conversationId must stick to the same engine—the two ChatMemory formats are incompatible, and users will experience "AI amnesia."
- Watch not "feels better" but four hard metrics: TTFT P95 / task completion rate / cost per conversation / human handoff rate.
- If metrics fail, one-config rollback. A reversible decision turns the bet into an option.
Version governance: pin framework and model versions with BOM double-pinning; run a fixed evaluation set for regression before upgrades; CI runs a dual-version matrix. Frameworks and model ecosystems iterate monthly; pinning old versions invites vulnerabilities, chasing new versions invites breakage. Small teams spending half a day quarterly on dependency tracking is enough.
9. Wrap-up: frameworks depreciate, boundaries appreciate
Condense the whole post into a few sentences:
- First set the runtime stack and Boot version—that's the hard constraint: Boot 4 projects prefer Spring AI 2.0; Boot 3 holdouts go 1.1.x transition or LangChain4j; non-Spring / multi-runtime go straight to LangChain4j.
- Then look at RAG complexity and vendor long tail: standard Q&A with enterprise monitoring consistency → Spring AI; complex retrieval pipelines, niche models/vector stores, multi-agent → LangChain4j; when complexity explodes, hand to a dedicated orchestration runtime.
- Regardless of choice, stand up
LlmPorton day one: abstraction layer isolates vendor lock-in, retrieval stages are replaceable and A/B-able, token and trace instrumentation goes live Day-one, ArchUnit welds the boundary shut. - Implementation order: ACL → virtual threads for concurrency → tune RAG's seven stages → progressive tool disclosure → gray-release dual-run validation.
The cost of picking the wrong framework is a refactor; the cost of picking the wrong abstraction is reworking the entire AI capability. I never bet on Spring AI or LangChain4j winning; I bet on keeping the cost of replacing them under 2 person-days.
If you're also doing Java + AI integration, follow me. Later I'll expand on "tool idempotency + local transaction alignment" and "RAG evaluation set construction."
Final interaction question for the comments: Has framework type leaked into your business layer in your current AI call chain? If you had to switch model vendors tomorrow, how many files would you estimate you'd change? Leave a number and see whose ACL is cleanest. If useful, hit like and share with a colleague agonizing over the same choice.
Top 3 of 7 from juejin.cn, machine-translated. The original thread is authoritative.
This piece really explains that 'framework selection is actually the cost of platform upgrade.' We've encountered similar problems when building Agent applications: to integrate one model, we ended up upgrading the whole Spring Boot, and the rollback cost later was much higher than the model invocation fee. I want to ask: where did you put the anti-corruption layer? Is it at the Service interface, or a standalone adapter module?
666, I feel this pain lol. We didn't put it on the business Service; we split out a dedicated adapter module. The business layer only depends on its own defined LlmPort and doesn't directly import AI framework packages; ArchUnit enforces the boundary. Framework-specific logic like RAG and Agent orchestration stays inside the adapter and doesn't leak out; we only abstract the minimal stable capabilities. Later, when changing or rolling back frameworks, only the adapter is touched; business code doesn't need changes.
This adapter approach is clean; ArchUnit enforcing the boundary is more reliable than verbal agreement. We later also kept the tool-calling schema outside the port, so when switching models we only change the serialization adapter. One question: does your contract testing only cover happy path, or does it also include timeout and rate limiting?
This article is brutally honest. The cost of choosing the wrong framework is a refactor; the cost of choosing the wrong abstraction is a rewrite of the entire AI capability. That line hits home. I'm taking note of the ArchUnit trick to weld the boundary shut.
Haha, 6, thanks for the recognition! Indeed, abstracting wrong is more fatal than switching frameworks. ArchUnit's move is to define the red line in advance, so boundaries aren't slowly crossed and things don't become coupled without notice 😁
Let me add a point that's easy to miss about the anti-corruption layer: if you directly annotate business methods with the framework's @Tool or ToolCallback, the framework type leaks back into the business class through the annotation, so you haven't actually prevented leakage. A more robust approach is to define your own capability description first (name, parameter schema, result code, whether it's retryable), then write a layer that adapts to the specific framework. Switching frameworks only requires changing the adapter layer. Also, the framework's built-in timeout/retry is dangerous for write operations by default: without an idempotency key, retrying a document creation leads to duplicate records. It's best to explicitly mark retryable=false per capability and hand the retry decision back to the business.
Great point, 666, you're right. I didn't cover these two points thoroughly in the article. The first one: I only prevented import in my original code; the example directly annotated the business class with @Tool, which brings the framework semantics back through the annotation, and ArchUnit can't stop that. Following your advice, defining the capability description first and then writing the adapter layer is cleaner; switching frameworks only touches the adapter layer. Second: an idempotency key is just a fallback; write operations should also explicitly retryable=false, leaving retry decision to the business, otherwise a document creation retries and creates duplicates. I'll add these two points to the tool section later. Thank you for the reminder.