Open
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
MongoClient
is passed from outside (not created by Spring),mongoInstanceCreated
is set tofalse
. -
Destroy Method Implementation
@Override public void destroy() { if (this.mongoInstanceCreated) { // Only closes if true this.mongoClient.close(); } }
The
destroy()
method only closes theMongoClient
ifmongoInstanceCreated
istrue
. -
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 = false
indicates "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
MongoClient
regardless ofmongoInstanceCreated
flag, OR - Provide a clear mechanism to handle externally created
MongoClient
instances