Skip to content

SimpleMongoClientDatabaseFactory does not close MongoClient when it's not registered as a Spring Bean #5012

Open
@jayjaehunchoi

Description

@jayjaehunchoi

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

  1. 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 to false.

  2. Destroy Method Implementation

    @Override
    public void destroy() {
        if (this.mongoInstanceCreated) { // Only closes if true
            this.mongoClient.close();
        }
    }

    The destroy() method only closes the MongoClient if mongoInstanceCreated is true.

  3. 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 of mongoInstanceCreated flag, OR
  • Provide a clear mechanism to handle externally created MongoClient instances

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions