Spring Boot 4 + Spring AI 2.0: Count the Migration Debt Before You Touch the Version Number
Spring Boot 4 + Spring AI 2.0 Migration in Practice: Don't Rush the Version Number, First Count the Debt You Owe
Last month at the team review, the business side slammed the table: 'The competitor's intelligent customer service is already live. When can our Spring AI 2.0 run?' I opened the project's pom.xml and looked: Boot 3.5, Jackson 2, a pile of javax leftovers, 217 @MockBean annotations. I said: this can't be rushed. The bill has to be calculated first, or we are building on quicksand.
This article is for people stuck on the 'Boot 3.x → Boot 4 + Spring AI 2.0' path. It does not list new features; it covers one thing: how to inventory, prioritize, and pay off this migration debt. Every pitfall below is one I or teams around me have actually walked through.
1. A bucket of cold water: this is not an 'upgrade', it is a technical debt settlement
First, nail down the most important fact:
Spring AI 2.0's baseline is Spring Boot 4.0/4.1 + Spring Framework 7. It cannot be loaded in a Boot 3.x classpath at all. Spring's official wording is 'cannot be loaded in a 3.x context'.
I hit this last year: I thought I could add Spring AI 2.0 before Boot, but the starter was imported and startup immediately threw ClassNotFoundException, stuck on Jackson coordinates. Since then I have a habit: run a dependency radar scan before talking about AI.
The time bill: why this can neither be delayed nor rushed
Today is December 2, 2026.
| Version line | Key event | OSS support window | My judgment |
|---|---|---|---|
| Boot 3.5 | Last patch 3.5.16 (2026-06-25) | Ended 2026-06-30 | Can only survive on commercial support; security patches are no longer public |
| Boot 4.0 | GA 2025-11-21 | Expires 2026-12-31, only one month left | Most tutorials, but you can't stop here |
| Boot 4.1 | GA 2026-06-10 | Until 2027-07-31 | Current best landing point |
| Boot 4.2 | GA 2026-11-19 | Until 2027-12-31 | Too new; you'll take the first wave of hits yourself |
| Spring AI 2.0.x | GA 2026-06-12, baseline Boot 4.0/4.1 | Stable | The only dual-stable combination with Boot 4.1 |
| Spring AI 2.1 | GA 2026-11-20, baseline Boot 4.2 | Stable | Requires moving to Boot 4.2 as well |
The conclusion in one sentence: target JDK 21 + Boot 4.1 + Spring AI 2.0.x. Don't stay on 4.0, and don't jump two major versions at once. If something breaks, you won't know whether it is the framework's fault or the AI layer's.
One correction that can save two weeks of useless scheduling: Boot 4 still requires Java 17 as a minimum, not 21. 21 is recommended because virtual threads and GraalVM native images work noticeably better; only native-image strictly requires GraalVM 25+. Virtual threads, RestClient, and similar features existed in late Boot 3.x. Don't count them as new debt and re-verify them.
2. Look at this dependency tower: your debt is in the foundation
AI 2.0 stands at the tip; your debt is in the foundation. Spring AI is the finished interior, Boot 4 is the load-bearing wall. If you do the interior before the wall is built, you end up reworking both ends.
The debt splits into three layers: foundation debt → framework debt → AI adaptation debt. The first layer must be zero before anything else; the second determines the workload; the third is the debt Spring AI 2.0 actually adds. Below, layer by layer.
3. Foundation debt: Jackson 3 is the sneakiest item
3.1 javax → jakarta: it compiles, but the feature is gone
Framework 7 is based on Jakarta EE 11, and javax.* is completely gone. Global replacement is grunt work; the truly nasty part is this:
Condition annotations like @ConditionalOnClass("javax.servlet.Servlet") that were not updated do not report an error; auto-configuration silently fails. The service starts normally, the health check is UP, but the feature is gone. This kind of silent failure is ten times scarier than a compile error.
The fix is simple and crude: add a CI rule that fails the build when a non-whitelisted grep -r "javax." src/ hit appears. Then use Enforcer to block javax at build time:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-enforcer-plugin</artifactId>
<configuration>
<rules>
<bannedDependencies>
<excludes><exclude>javax.*:*:*:*:compile</exclude></excludes>
<message>javax dependency found; in the Boot 4 world it is an illegal structure!</message>
</bannedDependencies>
</rules>
</configuration>
</plugin>
3.2 Jackson 3: package rename is only the surface; contract breakage is the killer
Boot 4 prefers Jackson 3, and the package moves from com.fasterxml.jackson to tools.jackson. Pay attention to the details:
- Annotations stay in com.fasterxml.jackson; jackson-annotations does not change package. Don't do a blind global replace.
- ObjectMapper / JsonMapper can only be built through the builder, and are immutable after construction. All customization must happen in the builder phase.
- Jackson2ObjectMapperBuilderCustomizer becomes JsonMapperBuilderCustomizer.
- MappingJackson2HttpMessageConverter is deprecated; the replacement is JacksonJsonHttpMessageConverter. Redis and Kafka serializers must be updated too, or cross-service deserialization blows up.
- Jackson 2 remains in deprecated form via spring-boot-jackson2, but will be removed in 7.2.
AI scenarios depend on Jackson far more deeply than ordinary web applications: structured output, Tool JSON Schema, MCP SDK, vector store metadata, and ChatMemory serialization all sit on Jackson. Treat this debt as P0 in AI projects.
The most insidious items are two silent breakages:
First, exceptions become unchecked, so old fallback logic goes deaf:
// ❌ Jackson 2 era code; in Jackson 3 this catch compiles but catches nothing
try {
return mapper.readValue(payload, Order.class);
} catch (IOException e) {
// Jackson 3: all exceptions are unchecked (JacksonException extends RuntimeException)
// readValue no longer declares throws; the compiler doesn't complain, but this catch never runs
return Order.empty();
}
Fix: globally grep all catch (IOException), JsonProcessingException, JsonMappingException, and JsonParseException, and treat them as first-class work items.
Second, six serialization defaults flip. The worst is WRITE_DATES_AS_TIMESTAMPS changing from enabled to disabled. Date fields quietly change from numeric timestamps to ISO-8601 strings. Your external JSON contract changes, and downstream consumers parsing the old format break.
My crude but extremely effective verification: hit a real endpoint before and after the upgrade and diff the output, focusing on dates, nulls, and defaults:
curl -s http://localhost:8080/api/order/1 > before.json # before upgrade
curl -s http://localhost:8080/api/order/1 > after.json # after upgrade
diff before.json after.json | head -50
During transition, spring.jackson.use-jackson2-defaults: true can hold things together for a while, but don't rely on it long term. If the bridge stays, it becomes architecture.
If some components (such as an MCP SDK or old model SDK that has not adapted yet) must use Jackson 2 in the short term, you can do a dual-stack isolation, but use a trick:
@Configuration(proxyBeanMethods = false)
// Assemble only while the debt still exists: active only if Jackson 2 is still on the classpath; disappears automatically once the debt is paid
@ConditionalOnClass(name = "com.fasterxml.jackson.databind.ObjectMapper")
class JacksonBridgeConfig {
/** For components that have not migrated to Jackson 3; not part of web serialization */
@Bean("legacyJackson2Mapper")
com.fasterxml.jackson.databind.ObjectMapper legacyJackson2Mapper() {
return com.fasterxml.jackson.databind.json.JsonMapper.builder().build();
}
/** Main line uses Jackson 3 uniformly */
@Bean
tools.jackson.databind.json.JsonMapper aiJsonMapper() {
return tools.jackson.databind.json.JsonMapper.builder()
// Pin the external contract explicitly, or date formats quietly change
.enable(tools.jackson.databind.SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
.build();
}
}
Technical highlight: @ConditionalOnClass gives transitional code a built-in expiry mechanism. Once the debt is paid, the bridge bean disappears and does not become permanent technical debt. This idea can be generalized to all migration transitional code.
Health-check method: globally search for com.fasterxml.jackson imports and tag them into four categories: annotations / ObjectMapper beans / custom Serializer / Deserializer. Annotations mostly stay; the other three migrate item by item. On the AI side, additionally verify the .entity() structured output path.
4. Framework debt: the four bills that determine workload
4.1 Starter modularization: implicit dependencies are all exposed
Boot 4 splits the old monolithic spring-boot-autoconfigure into focused modules. spring-boot-starter-web becomes spring-boot-starter-webmvc, and Flyway/Liquibase must explicitly depend on spring-boot-starter-flyway.
In the Boot 3.x era, one starter pulled in autoconfigure as one big jar. After Boot 4 splits it, capabilities that are not explicitly declared simply disappear. Typical symptoms: @ConditionalOnClass stops matching, DataSource auto-configuration does not take effect, compilation passes, and migration scripts silently do not run.
Two key actions:
First, large projects should use the official transition bridge to get a green build:
Technical highlight: Boot 4 provides spring-boot-starter-classic / spring-boot-starter-test-classic, which package all the modularized autoconfigure modules. Use it first to get running, then replace it one by one with precise module dependencies. This is the official escape hatch for gradual migration. But give the classic dependency an exit deadline, and make CI warn when it expires, or it will become permanent architecture.
Second, teams with custom starters will pay real blood. Auto-configuration classes are no longer read from META-INF/spring.factories; they move to META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports. In Boot 4, many internal auto-configuration class members become package-private. Code that used to inherit internal classes will fail compilation. Stop inheriting; use composition or conditional assembly.
Health-check commands:
# Find all modules still using the old spring.factories
find . -path '*/META-INF/spring.factories' -print
# Find code that directly references Spring Boot internal auto-configuration
grep -rn "org.springframework.boot.autoconfigure" --include='*.java' | grep -v "AutoConfiguration.imports"
Then use ApplicationContextRunner to turn 'I think it will take effect' into 'it must take effect in CI':
@Test
void chatClientAutoConfig_shouldLoad_whenStarterPresent() {
new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(AiAutoConfiguration.class))
.withPropertyValues("spring.ai.openai.api-key=test")
.run(ctx -> assertThat(ctx).hasSingleBean(ChatClient.class));
}
4.2 Virtual threads on by default: old thread pool config can become a liability
In Boot 4, spring.threads.virtual.enabled defaults to true. Tomcat/Jetty request-handling threads and @Async tasks run on virtual threads by default. This affects AI applications more than ordinary CRUD: tool calls, RAG retrieval, and multi-turn dialogue are I/O intensive and can block for a long time, so virtual threads are the right direction.
But there are two pitfalls:
// ❌ Typical Boot 3.x 'big pool' config; an anti-pattern under virtual threads
@Bean
ThreadPoolTaskExecutor aiTaskExecutor() {
var executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(50); // This number loses its original meaning under virtual threads
executor.setMaxPoolSize(200);
executor.setQueueCapacity(1000);
return executor;
}
// ✅ Let virtual threads take over I/O-intensive AI calls; @Async already schedules on virtual threads by default
// The only real need for platform thread pools is CPU-intensive post-processing (local embedding, reranking)
Pit one: ThreadLocal leakage is amplified. Virtual threads can create millions of instances. ThreadLocal values that were 'a small leak you could tolerate' in a platform thread pool can become a memory problem. Worse, when @Tool methods run in parallel, the SecurityContext / MDC / tenant context in ThreadLocal can be lost. This took me two days to debug. Solution: use context-propagation to snapshot explicitly, or pass parameters explicitly.
Pit two: synchronized pinning. If the underlying SDK (some embedding / VectorStore clients) heavily uses synchronized plus blocking I/O, it can pin the carrier thread, and throughput can drop instead of rising. During load testing, enable -Djdk.tracePinnedThreads=full (JDK 24+ has fixed most pinning), and put AI calls in their own bulkhead so they don't drag down web threads.
A side question: if you introduced WebFlux / Reactor for 'high concurrency' back then, now ask seriously: synchronous code plus virtual threads already gets comparable throughput. Does the reason for a reactive stack still hold?
4.3 JSpecify null safety: AI code's historical 'gentleman's agreement' with null is broken
Boot 4 and Spring AI 2.0 use JSpecify annotations throughout. By default, API return values and parameters are non-null, and anything nullable must be explicitly marked @Nullable. AI applications are exactly where compile warnings are easiest to hit: model-returned content can be null, tool call return values can be null, and the last chunk of a streamed response can be null.
// package-info.java
@org.jspecify.annotations.NullMarked
package com.acme.ai.rag;
public record Hit(String docId, double score,
@Nullable String chunkText) {} // Explicitly nullable when retrieval misses
In AI scenarios, 'model didn't return / tool had no result / vector search missed' is normal. Null safety is not pedantry; it is the front line against NPE. But don't get carried away and add @NullMarked to the whole project at once. Roll it out package by package, and turn on the CI gate for incremental convergence. Kotlin teams also need to watch platform types.
4.4 Test stack + containers + miscellaneous
None of these bills is large alone, but together they add up:
| Debt item | Change | Notes |
|---|---|---|
| Test annotations | @MockBean / @SpyBean removed → @MockitoBean / @MockitoSpyBean (note the attribute is answers, not answer); @WebMvcTest moves to spring-boot-starter-webmvc-test; @AutoConfigureMockMvc must be explicit |
Large volume but automatable |
| Containers | Undertow removed (not adapted to Servlet 6.1); only Tomcat 11 / Jetty 12.1 | Container switch needs a full performance regression: large file upload timeout, WebSocket, async thread model |
| HttpHeaders | Framework 7 no longer implements MultiValueMap | Utility methods that pass it as a Map fail compilation directly |
| Observability | Unified OpenTelemetry; new spring-boot-starter-opentelemetry; management.tracing.enabled → management.tracing.export.enabled | Attach spring-boot-properties-migrator to scan renamed configuration |
| Security 7 | Lambda DSL, PathPatternRequestMatcher | SSE endpoints and tool callbacks are the easiest to get blocked by authorization / CSRF |
| Hibernate 7 | SQL / dialect / naming strategy changes | RAG metadata filter queries are sensitive; do SQL snapshot comparison |
// Boot 4 style
@SpringBootTest
@AutoConfigureMockMvc // 4.0 no longer auto-assembles it
class AgentServiceTest {
@MockitoBean
private ChatModel chatModel;
@Test
void shouldReturnAnswerWhenChat() {
when(chatModel.call(any(Prompt.class)))
.thenReturn(new ChatResponse(List.of(new Generation("ok"))));
// ...
}
}
Don't be afraid of test refactoring volume. We had 2,000 test classes; an OpenRewrite recipe ran in batch and cleaned them up in two days.
5. AI adaptation debt: the bill Spring AI 2.0 actually adds
Finishing the Boot 4 upgrade only gets you a ticket. Spring AI 2.0 redefines boundaries at the framework level, and this debt is the most underestimated. Many people think 'Boot to 4, Spring AI just changes a version number.'
| Dimension | 1.x debt | 2.0 repayment |
|---|---|---|
| Entry API | ChatClient / ChatModel mixed; business injects ChatModel directly | ChatClient is the user-facing API; ChatModel returns to being a lower-level building block |
| Options | Created via constructors, mutable, defaults scattered | Builder-created, immutable, defaults unified into the options layer |
| Tool call loop | Each ChatModel implementation writes its own | Unified into ToolCallingAdvisor; ChatClient auto-registers it |
| MCP transport | SSE | Streamable HTTP becomes the default |
| Provider SDK | Hand-written OpenAiApi / AnthropicApi facades | Facades removed; official SDKs are used directly |
| Starter coordinates | spring-ai-openai-spring-boot-starter | spring-ai-starter-model-openai |
5.1 Options: from mutable objects to strictly immutable
// ❌ Spring AI 1.x: builder uses withXxx, sometimes even new + runtime field mutation
var options = OpenAiChatOptions.builder()
.withModel("gpt-4o")
.withTemperature(0.3)
.build();
// ✅ Spring AI 2.0: builder-created, immutable
var options = OpenAiChatOptions.builder()
.model("gpt-4o")
.temperature(0.3)
.build();
// Need to change existing options? Use mutate(), not copy()
OpenAiChatOptions requestOptions = defaultOptions.mutate()
.model("your-model")
.temperature(0.1)
.build();
Naming is also unified: OllamaOptions → OllamaChatOptions, and all XxxOptions become XxxChatOptions.
There is an easily ignored behavior difference:
- At the ChatModel layer: when a request carries Options, the request Options win; ChatModel is not responsible for merging.
- At the ChatClient layer: merging of default parameters and request parameters is supported.
So the same request can produce different results when called directly on ChatModel versus through ChatClient. During migration, make parameter priority explicit: layer global default configuration and request configuration, and add override tests.
Also note the ChatClient.options() signature change: 1.x accepted a built Options object; 2.0 only accepts a Builder, not an instance. Use .options(OllamaChatOptions.builder().temperature(0.2)), and don't call .build().
5.2 Tool calling: the execution location changed, and this is the sneakiest silent bug
In 1.x, the tool loop was hidden inside each model implementation, so no hooks could be inserted. In 2.0, it is promoted to a first-class citizen on the advisor chain, managed uniformly by ToolCallingAdvisor, auto-registered by ChatClient. The old internalToolExecutionEnabled configuration is gone.
The benefit is that you can add guardrails to the tool chain (round limits, token budgets, audit), and even use ToolSearchToolCallingAdvisor for progressive tool disclosure up to hundreds of tools. But there are two pitfalls:
⚠️ Pit one: at most one ToolAdvisor per chain. ChatClient already auto-registers one. If you manually add
.advisors(new ToolCallingAdvisor(...)), tools execute twice. It doesn't error, but the behavior changes. An advisor that manages its own lifecycle should declare the ToolAdvisor marker to avoid collision.⚠️ Pit two: calling ChatModel.call() directly returns only the first tool-call response; the loop does not run automatically. Either drive it with ChatClient, or drive it yourself with ToolCallingManager. Any hand-written loop in existing code should be deleted during this migration.
Tool definitions also need a rewritten security boundary. The model only proposes the intent to call; permission checks, parameter validation, idempotency, and audit must stay inside the Java service:
@Component
public class OrderTools {
private final OrderService orderService;
public OrderTools(OrderService orderService) {
this.orderService = orderService;
}
@Tool(description = "Query the current user's order status. Read-only; performs no modification")
public OrderView queryOrder(
@ToolParam(description = "Order number") String orderNo) {
// User identity comes from the trusted session; never let the model pass a userId to decide query scope
CurrentUser user = CurrentUserHolder.required();
// Parameter validation, permission checks, and audit are all executed server-side
return orderService.queryOwnedOrder(user.id(), orderNo);
}
}
I recommend splitting tools into 'read-only query' and 'business write' categories. Write operations must be idempotent; high-risk operations need human confirmation; the tool loop needs limits on rounds and total time. Also, the AI security surface is genuinely expanding: model output can drive dynamic external URL access, turning SSRF from a paper risk into a real threat. Tool calls should go through a whitelist plus an outbound proxy, and Boot 4.1 with HTTP Client SSRF mitigation is the preferred base.
5.3 The correct way to use ChatClient
Injecting ChatClient.Builder rather than calling ChatClient.builder(chatModel) yourself is the watershed in 2.0:
@Configuration
class AiClientConfig {
@Bean
ChatClient chatClient(ChatClient.Builder builder,
ChatMemory chatMemory,
OrderTool orderTool,
CostGuardAdvisor costGuard) {
return builder
.defaultSystem("You are an order assistant. If you don't know, say so; don't make things up.")
// 2.0: pass a Builder, not an instance; Options are immutable and defaults are unified in the Options layer
.defaultOptions(OpenAiChatOptions.builder()
.model("gpt-4o-mini").temperature(0.2))
// 2.0: defaultToolCallbacks(...) is deprecated → use Object... directly
.defaultTools(orderTool)
// PromptChatMemoryAdvisor is removed; MessageChatMemoryAdvisor is built via its builder
.defaultAdvisors(
MessageChatMemoryAdvisor.builder(chatMemory).build(),
costGuard)
.build();
}
public String ask(ChatClient chatClient, String question) {
return chatClient.prompt()
.user(question)
// 2.0 requires CONVERSATION_ID explicitly; otherwise the Memory Advisor throws IllegalArgumentException
.advisors(a -> a.param(ChatMemory.CONVERSATION_ID, "user-001"))
.call()
.content();
}
public OrderAnswer askStructured(String q) {
return chatClient.prompt(q)
.tools(orderTool) // runtime tool override of defaults
.toolContext(Map.of("tenantId", TenantContext.get()))
.call()
.entity(OrderAnswer.class); // JSON Schema → Record
}
}
Properties configuration must change too. 2.0 flattens the .options. segment:
# ❌ Spring AI 1.x
spring.ai.ollama.chat.options.model=qwen2.5:3b
spring.ai.ollama.chat.options.temperature=0.2
# ✅ Spring AI 2.0
spring.ai.ollama.chat.model=qwen2.5:3b
spring.ai.ollama.chat.temperature=0.2
Attach spring-boot-properties-migrator (runtime scope), and startup logs will tell you which keys were renamed. Principle: let missing or invalid configuration explode at startup, not on the first NPE when you call the model.
5.4 Chat Memory: upgrading code without upgrading the table is a wasted upgrade
If you use JDBC Chat Memory, 2.0 adds a sequence_id column to determine message order within a conversation, avoiding order problems caused by inconsistent timestamp precision across databases. This is a runtime pit; compilation cannot detect it.
Use Expand → Backfill → Validate → Switch instead of stopping and rebuilding:
ALTER TABLE spring_ai_chat_memory
ADD COLUMN sequence_id BIGINT;
-- Group by conversation_id, backfill based on the original time order
-- After backfill, validate: null count, duplicate sequence numbers, total message count
-- Finally add NOT NULL constraint and a composite index
CREATE INDEX idx_chat_memory_conversation_sequence
ON spring_ai_chat_memory (conversation_id, sequence_id);
The actual backfill SQL must be adjusted per database dialect; don't run one PostgreSQL script everywhere. Back up before upgrading, and after upgrading sample-check message order per conversation. If the model suddenly seems 'amnesiac' or context is reversed, this is usually the cause.
Another forward-looking signal: ChatMemory and MessageChatMemoryAdvisor begin deprecation in 2.1, and the direction is the Session API, which models a conversation as an append-only event log rather than a flat message list, with support for context compaction and recall. Why? In the agent era, one user question can produce six messages (tool call + tool result × 2 + final answer), and window-style truncation can cut a complete logical exchange into pieces. New projects can evaluate the Session API directly; old projects should wait for 2.1 API stability.
The good news is that storage options are wider: 2.0 adds Redis Chat Memory, and Redis Vector Store now supports text search, range queries, and HNSW tuning. Teams that already have Redis can avoid deploying a separate vector database.
5.5 MCP and Provider SDK
- MCP transport: SSE → Streamable HTTP becomes the default. Self-built MCP server/client transport configuration must be rewritten. Don't mix in the 1.x MCP configuration model.
- MCP package migration: org.springaicommunity.mcp.annotation.* → org.springframework.ai.mcp.annotation.*. MCP annotations are now in core, so the separate community package is no longer needed. MCP 2.0 also adds JSON Schema validation for parameters.
// MCP 2.0: annotating a method exposes it as a tool
@McpTool(name = "query_order", description = "Query order status by order number")
public OrderDTO queryOrder(@McpToolParam(description = "Order number") String orderNo) {
return orderService.getByNo(orderNo);
}
- Provider SDK replacement: hand-written facades like OpenAiApi / AnthropicApi are deleted; use the official SDKs directly. OpenAI's default model moves to gpt-5-mini, and timeout/retry/rate-limit semantics need re-verification.
// ❌ 1.x
AnthropicApi anthropicApi = new AnthropicApi(apiKey);
AnthropicChatModel chatModel = new AnthropicChatModel(anthropicApi, options);
// ✅ 2.0
AnthropicChatModel chatModel = AnthropicChatModel.builder()
.apiKey(apiKey)
.defaultOptions(options)
.build();
⚠️ Behavior change warning: Anthropic's maxTokens default changes from 500 to 4096. If your business relied on 500 as a cap to prevent token overspend, upgrading to 2.0 could burn your API quota overnight. To preserve old behavior, explicitly set it back.
6. Dependency management: don't let two BOMs fight over the steering wheel
The Boot BOM manages base dependencies; the Spring AI BOM manages the AI ecosystem. Don't casually override the model SDK, JSON, or Reactor versions managed by the AI BOM:
<properties>
<java.version>17</java.version>
<spring-ai.version>2.0.0</spring-ai.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-bom</artifactId>
<version>${spring-ai.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webmvc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-model-openai</artifactId>
</dependency>
</dependencies>
Use the dependency tree and Enforcer as a safety net:
./mvnw dependency:tree -Dverbose
./mvnw enforcer:enforce
# Pre-upgrade check
./mvnw versions:display-dependency-updates
In Enforcer, turn on dependencyConvergence and banDuplicatePomDependencyVersions. Use a whitelist to block Jackson 2: only transitional components are allowed to use it, so third-party SDK transitive dependencies can't pull it back into the main line:
<bannedDependencies>
<excludes><exclude>com.fasterxml.jackson.core:jackson-databind</exclude></excludes>
<includes><include>com.fasterxml.jackson.core:jackson-databind:2.20.*</include></includes>
<message>Jackson 2 is limited to transitional components; web/serialization uses Jackson 3</message>
</bannedDependencies>
Key point: don't blindly exclude a red conflict. First determine whether the excluded package belongs to Jackson, a model SDK, or a Spring extension interface. AI projects have a much messier dependency graph than web projects; one cut can hit an artery.
A lazy trick: Spring AI provides an official OpenRewrite recipe that handles most mechanical changes (imports, method renames, dependency coordinates):
mvn org.openrewrite.maven:rewrite-maven-plugin:6.32.0:run \
-Drewrite.configLocation=https://raw.githubusercontent.com/spring-projects/spring-ai/refs/heads/main/src/rewrite/migrate-to-2-0-0-M3.yaml \
-Drewrite.activeRecipes=org.springframework.ai.migration.M3*
But it cannot catch code that directly depends on lower-level provider API classes (such as OpenAiApi); those must be inspected by hand. Community testing has also shown that the UpgradeSpringBoot_4_0 recipe can change ObjectMapper to the wrong type. After running it, review every change with git diff; do a dry-run first, then apply.
7. Turn debt into checkable engineering constraints
7.1 Startup probe: better to fail in pre-prod than NPE in production
@Component
@Profile({"ci", "staging"}) // Not enabled in production; moved left into the pipeline
class MigrationGuard implements ApplicationRunner {
private final ConfigurableListableBeanFactory bf;
private final Environment env;
MigrationGuard(ConfigurableListableBeanFactory bf, Environment env) {
this.bf = bf;
this.env = env;
}
/** The sneakiest post-Boot-4 modularization pit: condition mismatch → bean silently disappears, yet startup 'succeeds' */
private static final List<Class<?>> MUST_EXIST = List.of(
ChatModel.class, VectorStore.class, ChatMemory.class,
ChatClient.Builder.class, PlatformTransactionManager.class);
@Override
public void run(ApplicationArguments args) {
// Critical bean assertions
var missing = MUST_EXIST.stream()
.filter(t -> bf.getBeanNamesForType(t).length == 0)
.map(Class::getSimpleName).toList();
if (!missing.isEmpty()) {
throw new IllegalStateException("Boot4 migration debt not cleared; auto-configuration silently failed: " + missing);
}
// javax still on the classpath means old dependencies were not cleaned up
ClassLoader cl = Thread.currentThread().getContextClassLoader();
for (String clazz : List.of("javax.servlet.Filter", "javax.persistence.Entity")) {
try {
Class.forName(clazz, false, cl);
throw new IllegalStateException("Old javax dependency found: " + clazz);
} catch (ClassNotFoundException ok) {
// expected
}
}
// AI keys must be injected through config center
if (env.getProperty("app.ai.enabled", Boolean.class, false)
&& !env.containsProperty("app.ai.api-key")) {
throw new IllegalStateException("AI Key was not injected through config center");
}
}
}
Pair it with ArchUnit to prevent debt from growing back:
@AnalyzeClasses(packages = "com.company")
class MigrationArchTest {
@ArchTest
static final ArchRule no_javax = noClasses()
.should().dependOnClassesThat()
.resideInAnyPackage("javax..")
.because("The Boot 4 stack should be unified on jakarta.*");
@ArchTest
static final ArchRule noJackson2 = noClasses().that().resideInAPackage("..ai..")
.should().dependOnClassesThat()
.resideInAPackage("com.fasterxml.jackson.databind..");
}
Also diff the /actuator/conditions report before and after the upgrade. It is the most direct evidence for finding 'disappeared beans'.
7.2 AI anti-corruption layer: don't bind business code to one version's API
Spring AI iterates fast. Advisor and Memory APIs changed frequently even in 1.x, and 2.1 is pushing the Session API. The criterion for whether you need an anti-corruption layer is simple: have AI SDK types leaked into business modules? Once leaked, every minor change forces a full-project scan.
@ConfigurationProperties(prefix = "app.ai")
@Validated
record AiProperties(
@NotBlank String model,
@NotBlank String promptVersion,
@NotNull Duration timeout,
@Positive int topK,
@NotEmpty Set<String> allowedTools
) {}
record AiRequest(String traceId, String tenantId, String question, String tool) {}
record AiAnswer(String content, String model, long totalTokens, boolean degraded) {}
interface AiGateway {
AiAnswer rag(AiRequest req);
}
@Service
class SpringAiGateway implements AiGateway {
private final ChatClient chatClient;
private final ChatOptions chatOptions; // vendor-specific, contained in infrastructure layer
private final Advisor ragAdvisor;
private final AiProperties props;
private final MeterRegistry meter;
// Constructor injection omitted
@Override
@Timed(value = "ai.rag", extraTags = {"scene", "rag"})
@Retry(name = "llm") // In production, retry only 429/5xx/connection timeout, and cap the token budget
@CircuitBreaker(name = "llm", fallbackMethod = "degrade")
public AiAnswer rag(AiRequest req) {
if (req.tool() != null && !props.allowedTools().contains(req.tool())) {
throw new IllegalArgumentException("Tool not authorized: " + req.tool());
}
ChatResponse resp = chatClient.prompt()
.system("You are an enterprise knowledge base assistant; answer only based on retrieved evidence; say so when uncertain.")
.user(req.question())
.advisors(ragAdvisor)
.options(chatOptions)
.call()
.chatResponse();
String content = resp.getResult().getOutput().getContent();
var usage = resp.getMetadata().getUsage();
long tokens = usage == null ? 0 : usage.getTotalTokens();
meter.counter("ai.token.total",
"model", props.model(),
"prompt", props.promptVersion(),
"tenant", req.tenantId() == null ? "unknown" : req.tenantId())
.increment(tokens);
return new AiAnswer(content, props.model(), tokens, false);
}
public AiAnswer degrade(AiRequest req, Throwable t) {
meter.counter("ai.degrade", "reason", t.getClass().getSimpleName()).increment();
// Critical: degradation does not fabricate a generative answer
return new AiAnswer(
"The model service is busy; generative answers are disabled. Please use the knowledge base retrieval entry.",
"fallback", 0, true
);
}
}
The technical highlights are concentrated in this design: business depends only on the AiGateway facade; prompt version is server-controlled and clients cannot pass it; tool whitelist validation; token metering by model/tenant/prompt version; circuit-breaker fallback never fabricates answers. Combined with ArchUnit banning business packages from importing org.springframework.ai, the change stays contained in one package.
7.3 Token cost governance: the best use of the advisor chain model
Three months after an AI launch, the thing that slaps you is usually not the technology; it is the bill. A custom Advisor plugs in and out like a Filter, with zero business invasion:
@Component
public class TokenBudgetAdvisor implements CallAdvisor {
private final TokenBudgetRepository budget;
@Override public String getName() { return "tokenBudgetAdvisor"; }
@Override public int getOrder() { return Ordered.HIGHEST_PRECEDENCE + 10; }
@Override
public ChatClientResponse adviseCall(ChatClientRequest req, CallAdvisorChain chain) {
String userId = (String) req.context().get("userId");
int estimated = estimateTokens(req); // Simple character-count estimate is enough
// Reserve quota before doing work, to prevent overselling under concurrency
if (!budget.tryReserve(userId, estimated)) {
throw new QuotaExceededException("Daily AI quota used up; please come back tomorrow.");
}
ChatClientResponse response = chain.nextCall(req);
// Settle with real usage; refund the difference
response.chatResponse().getMetadata().getUsage().ifPresent(usage -> {
budget.settle(userId, estimated, usage.getTotalTokens());
log.info("AI call userId={} prompt={} completion={} total={}",
userId, usage.getPromptTokens(),
usage.getCompletionTokens(), usage.getTotalTokens());
});
return response;
}
}
One reminder: don't use log.info to collect token statistics. ChatClient / Advisor / ChatModel / Tool / VectorStore each have Micrometer Observations; a unified Trace ID strings together 'what was asked → what was retrieved → what the tool returned → what the model output'. On monitoring, one metric matters: per-request model call count exposes a runaway tool loop earlier than average RT. One agent round may call the model four times, and average RT will not show it. Prompt content is not written to logs and spans by default; enable desensitized logging only when needed.
7.4 Streaming dividends and dark pits
@RestController
class ChatController {
private final ChatClient chat;
@GetMapping(value = "/ai/chat", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
Flux<String> chat(@RequestParam String q, @RequestParam String cid) {
return chat.prompt().user(q)
.advisors(a -> a.param(ChatMemory.CONVERSATION_ID, cid))
.stream().content()
.timeout(Duration.ofSeconds(30)) // A stuck upstream model must not drag down the gateway
.doOnCancel(() -> log.info("Client disconnected → cancel upstream to save tokens"))
.onErrorResume(TimeoutException.class,
e -> Flux.just("[degraded] Model busy, please try again later"));
}
}
spring:
threads:
virtual:
enabled: true
mvc:
async:
request-timeout: 60s # In SSE scenarios, don't let the default async timeout cut the stream
Dark pit: under SSE streaming, the trace breaks. The request thread and the Flux subscription thread are not the same, and MDC is lost directly. The fix is to put the trace context into Reactor Context instead of ThreadLocal:
return chatClient.prompt().user(q).stream().content()
.contextWrite(ctx -> ctx.put("traceId", MDC.get("traceId")))
.doOnNext(chunk -> log.info("chunk len={}", chunk.length()));
7.5 Native Image: don't wait until packaging to explode
In AI scenarios, Tool parameter schemas, Record binding, and JSON serialization are high-frequency Native Image pitfalls. @Tool uses reflection; it runs fine locally and crashes in a native image:
@Configuration(proxyBeanMethods = false)
@RegisterReflectionForBinding({
AiRequest.class, AiAnswer.class, ToolArg.class, ToolResult.class
})
class AiNativeHints {}
// @Tool classes also need registration
class AiHints implements RuntimeHintsRegistrar {
@Override
public void registerHints(RuntimeHints hints, ClassLoader cl) {
hints.reflection().registerType(OrderTools.class,
MemberCategory.INVOKE_DECLARED_METHODS,
MemberCategory.DECLARED_FIELDS);
}
}
The solution is a four-piece set: RuntimeHints + @RegisterReflectionForBinding + nativeTest in CI + contract tests. GraalVM 25+ is the floor.
8. How to quantify the debt: don't guess; use tools to score
A hand-waved answer to 'how much do we owe' is not convincing. In my project, I run these four checks and produce a debt table with person-days:
# 1. Who quietly pulled Jackson 2 back in? (AI projects find this everywhere)
mvn dependency:tree -Dincludes=com.fasterxml.jackson.core:jackson-databind
# 2. Mechanical rewrite volume = number of affected files (dry-run first; only view diff, don't apply)
mvn org.openrewrite.maven:rewrite-maven-plugin:dryRun \
-Drewrite.activeRecipes=org.openrewrite.java.spring.boot4.UpgradeSpringBoot_4_0
# 3. Config property renames: temporarily attach spring-boot-properties-migrator; it prints at startup
# 4. The sneakiest item: diff /actuator/conditions before and after the upgrade
| Check dimension | Tool | My red line |
|---|---|---|
| javax.* leftovers | grep + OpenRewrite scan | Any existing > 0 is P0 |
| Dependency outdated/conflict | versions-maven-plugin / Enforcer | Dual versions = P0 |
| Deprecated API call sites | jdeprscan + japicmp | Every 100 sites ≈ 0.5 person-day |
| Invalid config properties | properties-migrator runtime probe | Zero warnings = done |
| Test refactoring volume | Count @MockBean occurrences | Estimate 50 per person-day |
If you want a number for your boss, use a weighted estimate: migration debt score = Σ(module weight × risk coefficient). Module weight: core transaction/AI chain = 3, ordinary business = 2, pure tool/batch = 1. Risk coefficient: Jackson contract exposure ×1.5, Undertow ×1.3, internal Starter ×1.4, reactive/WebFlux ×1.2.
My real data: in the last project, the inventory showed three P0 items, 11 Jackson 2 transitive paths, 217 @MockBean annotations, and four third-party starters without Boot 4 versions. The estimate was 18 person-days, split across two iterations. Another reference: for a 20-module service with an AI chain plus internal starters, platform migration is about 3-4 person-weeks and AI layer adaptation about 1-2 person-weeks. 60% of that time goes into verification, not code changes. Compilation passing does not mean the migration is complete; startup success does not mean database migrations ran.
9. Landing route: 'big-bang full upgrade' is not the only path
Route selection
The AI Gateway branch is the most pragmatic option I recommend: AI capabilities are naturally suited to independent deployment (long connections, quota isolation, independent scaling). Build a new independent AI gateway service on Boot 4.1 + Spring AI 2.0.x, and have old services call it through a declarative HTTP client with @HttpExchange. That confines the migration blast radius to one service. This is trading architecture for time, and it is better than forcing a full upgrade.
If the team really cannot move off Boot 4 in the short term, there is a transitional option to state clearly: Spring AI 2.x only accepts Boot 4, while LangChain4j has a minimum JDK 17 and its starter covers both Boot 3.5+ and Boot 4. Organizations that care about specification consistency fit Spring AI better, but the version foundation is a hard constraint; if you can't choose it, you can't choose it.
Four-stage route for monolith upgrade
Three iron rules:
- Only move one variable at a time. JDK upgrade, Boot upgrade, and AI framework upgrade go in three separate iterations. Don't stack them; when something breaks, you won't know whose fault it is, and rollback won't have a baseline. Get JDK 21 running on 3.5 first, then move the framework.
- Go 3.5 → 4.1, skip 4.0. 4.0 is the 'first major version to arrive', not a 'version to live on'.
- Before stage 3, don't merge a single AI 2.0 line. 1.x → 2.0 is major-surgery-level API change.
Debt repayment and business delivery are two pipelines; don't let them block each other. With ai.enabled=false, AI beans are not assembled at all, and the main line continues repaying debt and shipping. The AI module iterates on an independent branch and does independent canary releases.
10. Acceptance: don't look at 'it starts'; look at four lines
Compile line ── dependency convergence, extension points usable, no key classes missing
Behavior line ── JSON / Memory / Tool Calling / RAG regression passes
Data line ── no lost messages, no ordering problems, vector dimensions consistent
Ops line ── latency, error rate, and token cost are observable, and rollback is possible
A production-level verification checklist; every item corresponds to a silent change that can explode:
| Verification item | Check method | Why it is mandatory |
|---|---|---|
| JSON contract snapshot test | Snapshot every external API response before/after upgrade; byte-level compare | Jackson 3 default flips deform payloads |
| Jackson exception path coverage | grep catch (IOException) etc.; rewrite to the JacksonException family |
Unchecked exceptions make old catches ineffective |
| ChatMemory session regression | Send two questions with the same conversation id; verify memory retention and order | CONVERSATION_ID went from optional to required; JDBC schema adds a column |
| Tool call chain test | Trigger one tool call; assert exactly one tool round trip per request | ChatModel.call() behavior changed; duplicate registration executes twice |
| MCP integration verification | MCP server tool call + parameter validation | Package migration; MCP 2.0 adds JSON Schema validation |
| LLM output semantic comparison | Same prompt; compare 1.x vs 2.0 answer facts (order ID, category field), not wording | Provider SDK replacement can cause output style differences |
| RAG effect regression | Fixed corpus and question set; compare recall/hit/answer accuracy | Service normal but answer accuracy quietly dropping is the hardest to find |
How do you prove 'behavioral equivalence' under LLM uncertainty? Three-layer gate: temperature=0 + WireMock record/replay to lock the upstream → field-level assertions on structured output → a small eval set (200-500 labeled Q&A pairs) for regression. If metrics don't pass, don't release.
Gray rollout follows Shadow (real traffic recorded but not returned) → 1% → 5% → 20% → full. Any red light and a feature flag rolls back in one click. The precondition for rollback is that the data plane only adds, never modifies: ChatMemory table structure and vector metadata formats get compatible extensions; indexes use versions and aliases; before rollback, verify the old application can read the new structure.
Metrics to watch during gray release:
- P95/P99 latency and first-token time;
- model error rate, tool call failure rate, tool loop count;
- RAG retrieval hit rate and fixed eval set accuracy;
- per-request token cost (broken down by tenant/model/prompt version);
- ChatMemory message count and order anomalies.
Finally, deliver four reports to your boss: dependency report (BOM no conflicts, javax zero, SBOM traceable), test report (unit/integration/contract/native/replay eval), load test report (P95/P99, retry rate, circuit-breaker rate, token cost, connection pool), and gray release report (Shadow comparison, canary metrics, rollback drill records).
Final words
After counting this bill, the core conclusions are three sentences:
First, Spring AI 2.0's cost is not in the AI layer; it is in the Boot 4 platform layer. The three most expensive debts are Jackson 3's silent contract breakage, the dual-version dilemma of internal starters, and controllability of the AI tool call chain.
Second, the acceptance criterion is not compilation passing; it is behavioral equivalence, rollback-ability, and cost visibility. The most expensive part of migration is never changing code; it is 'after the change, not knowing what quietly changed.' If the budget only covers one thing, build the contract test suite and pin tool round-trip count, JSON structure, and Trace ID as assertions. After that, every later step can be fast.
Third, the debt was not created by AI; AI made it visible. Boot 3 covered for you; Boot 4 makes you sign for yourself. With a stable foundation, AI is capability. Without a stable foundation, AI is an amplifier.
Landing suggestion: this week, run mvn dependency:tree -Dverbose and grep -r "javax." src/, list the debt, and score it. Even if you don't upgrade now, that table is the leverage you need to ask your boss for schedule.
If this is useful, click 'watching'. Later I will package this migration checklist into a runnable OpenRewrite configuration. Follow to stay updated.
One interaction question: when your team does a major framework version upgrade, are you 'radical' (jump straight to the latest) or 'conservative' (wait for patches to stabilize)? What is the biggest pit you have stepped in? Tell us in the comments.
Version numbers and support windows are subject to the official Release Notes / Migration Guide; re-check the current GA version before landing.
Top 1 from juejin.cn, machine-translated. The original thread is authoritative.
I can't keep up with learning. I recently used AI to make a mini program: specializing in curing couple fights and family discord [melon-eating crowd].