user3334226
user3334226

Reputation: 151

make MongoClient instance as singleton

I have a java-spring web application using MongoDB as database. Below lines are used to connect to database.

public class SpringMongoConfig {
@Bean
public MongoClient mongo() throws Exception {
    ServerAddress serverAddress = new ServerAddress(databaseUri, databasePort);
    List<MongoCredential> credentials = (databaseAuthenticationEnabled) ? Arrays.asList(
            MongoCredential.createCredential(databaseUser, authenticationDatabase, databasePassword.toCharArray()))
            : null;
    return new MongoClient(serverAddress, credentials);         
}

}

In another class, how will i get this mongoClient instance?

Upvotes: 1

Views: 1257

Answers (1)

Eugene
Eugene

Reputation: 120968

I assume that SpringMongoConfig is actually annotated with @Configuration and thus:

You need to find your another class's Configuration and @Import the SpringMongoConfig, something like this:

 @OtherConfigOfAnotherClass
 @Import(SpringMongoConfig.class)

And then simply @Autowire the MongoClient in the Service.

Upvotes: 1

Related Questions