-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Closed
Labels
type: documentationA documentation updateA documentation update
Milestone
Description
Summary of why MongoClient is not closed when not registered as a Spring Bean
Problem Description
When SimpleMongoClientDatabaseFactory is created with a MongoClient that is not registered as a Spring Bean, the MongoClient is not properly closed during application shutdown, leading to resource leaks.
Root Cause Analysis
-
SimpleMongoClientDatabaseFactory Constructor Behavior
public SimpleMongoClientDatabaseFactory(MongoClient mongoClient, String databaseName) { this(mongoClient, databaseName, false); // mongoInstanceCreated = false }
When a
MongoClientis passed from outside (not created by Spring),mongoInstanceCreatedis set tofalse. -
Destroy Method Implementation
@Override public void destroy() { if (this.mongoInstanceCreated) { // Only closes if true this.mongoClient.close(); } }
The
destroy()method only closes theMongoClientifmongoInstanceCreatedistrue. -
Spring Lifecycle Management Principle
- Spring only manages the lifecycle of objects it creates (registered as Beans)
- External objects injected into Spring Beans are not automatically managed
mongoInstanceCreated = falseindicates "Spring did not create this MongoClient, so Spring will not close it"
Impact
- Resource Leaks: MongoDB connections remain active on the server side
- Connection Pool Exhaustion: May reach connection pool limits
- Server Resource Waste: MongoDB server continues to maintain inactive connections
- Timeout Issues: Connections eventually timeout after server-side timeout period
Expected Behavior
SimpleMongoClientDatabaseFactory should either:
- Close the
MongoClientregardless ofmongoInstanceCreatedflag, OR - Provide a clear mechanism to handle externally created
MongoClientinstances
Metadata
Metadata
Assignees
Labels
type: documentationA documentation updateA documentation update