简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM