繁体   English   中英

使MongoClient实例成为单例

[英]make MongoClient instance as singleton

我有一个使用MongoDB作为数据库的java-spring Web应用程序。 下面的行用于连接数据库。

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);         
}

}

在另一个类中,我将如何获得这个mongoClient实例?

我假设SpringMongoConfig实际上是用@Configuration注释的,因此:

你需要找到你的another class的配置和@ImportSpringMongoConfig ,是这样的:

 @OtherConfigOfAnotherClass
 @Import(SpringMongoConfig.class)

然后简单地@Autowire服务中的MongoClient。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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