Fix : MongoDB index creation API compatibility across Spring Data Mongo… #4894
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Fix MongoDB index creation API compatibility across Spring Data MongoDB versions
Problem
Spring AI 1.1.0 fails to start when
spring.ai.chat.memory.repository.mongo.create-indices=trueis configured with Spring Boot 3.4.x, throwing:Root Cause:
Spring Data MongoDB changed its index creation API between versions:
ensureIndex(IndexDefinition)is availablecreateIndex(IndexDefinition)is the new API,ensureIndexis deprecatedThe original code in
MongoChatMemoryIndexCreatorAutoConfigurationhardcodedcreateIndex(), which doesn't exist in MongoDB 4.2.x - 4.4.x, causing runtime errors for users on officially supported Spring Boot versions.Solution
Implemented a reflection-based fallback strategy to dynamically choose the correct method at runtime:
createIndex()first (for Spring Data MongoDB 4.5.x+)ensureIndex()ifNoSuchMethodExceptionoccurs (for 4.2.x - 4.4.x)IllegalStateExceptionwith clear error message if neither method is availableThis approach follows Spring AI's existing pattern for handling optional dependencies (see
SpringAiRetryAutoConfiguration).Testing
Successfully tested across multiple Spring Boot versions:
ensureIndex()ensureIndex()ensureIndex()createIndex()Test command:
mvn clean test -pl auto-configurations/models/chat/memory/repository/spring-ai-autoconfigure-model-chat-memory-repository-mongodbImpact
Related Issues
Fixes #4884
Checklist
Signed-off-bylinemainbranchSpringAiRetryAutoConfiguration)